I am trying to add a logo to my PDF file using PDFBox version 2.0.1. I have the following code:
public class PDFService {
public void createPdf() {
// Create a document and add a page to it
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
// Create a new font object selecting one of the PDF base fonts
PDFont font = PDType1Font.HELVETICA_BOLD;
ServletContext servletContext = (ServletContext) FacesContext
.getCurrentInstance().getExternalContext().getContext();
try {
PDImageXObject pdImage = PDImageXObject.createFromFile(
servletContext.getRealPath("/resources/images/logo.png"),
document);
PDPageContentStream contentStream = new PDPageContentStream(
document, page);
contentStream.drawImage(pdImage, 20, 20);
contentStream.beginText();
contentStream.setFont(font, 12);
contentStream.endText();
// Make sure that the content stream is closed:
contentStream.close();
// Save the results and ensure that the document is properly closed:
document.save("Hello World.pdf");
document.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I am getting the error javax.imageio.IIOException: Can't read input file! in the line
PDImageXObject pdImage = PDImageXObject.createFromFile(
servletContext.getRealPath("/resources/images/logo.png"),
document);
The path returned by servletContext.getRealPath is C:\Users\erickpezoa\Desktop\Multivision\Materials\apps\eclipse Kepler\eclipse\Projects\.metadata\.plugins\org.eclipse.core.resources\Servicios_Exequiales\build\weboutput\resources\images\logo.png
What am I doing wrong here?
logo.pngin that directory?ImageIO.read(new File(servletContext.getRealPath("/resources/images/logo.png")));- do you get an exception on that line? If yes, then it means that the file isn't there after all. (Maybe you checked at a different time), or that it hasn't the permissions needed.