Erick
Erick

Reputation: 833

Apache PDFbox Java getting error Cant read input file

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?

Upvotes: 0

Views: 2839

Answers (1)

OscarBcn
OscarBcn

Reputation: 626

If you are using Maven and your images folder is under src/main/resources in Eclipse, you can try:

PDImageXObject pdImage = PDImageXObject.createFromFile(
                PDFService.class.getResource("/images/logo.png").getPath(),
                document);

is only needed /resources/images/logo.png as path if under src/main/resources you have another folder called resources. Or not using Maven, and your output folder contains: /resources/images. In that case:

PDImageXObject pdImage = PDImageXObject.createFromFile(
                PDFService.class.getResource("/resources/images/logo.png").getPath(),
                document);

Hope it helps.

Upvotes: 3

Related Questions