Guy Stimpson
Guy Stimpson

Reputation: 87

PDFBox why is the image not appearing in the PDF output?

I have (I think) correctly followed the instructions from: https://memorynotfound.com/apache-pdfbox-add-image-pdf-document/

I am attempting to insert an image logo.png. The code runs and doesn't throw up any errors, but the resulting PDF does not contain an image! The text does appear as expected. Does anybody know why this is and how to fix it? I'm using Java 8 in Apache NetBeans 11.

Thanks. Here's the code:


    public void generate(File samplefile) throws IOException {
        PDDocument document = new PDDocument();
        //Adding the blank page to the document
        //Repeat this next line for further pages
        PDPage page = new PDPage();
        document.addPage(page);
        File dir = new File(ArdenRecord.sadd + "/Sample Reports");
        if (!dir.exists()) {
            dir.mkdir();
        }
        String fname = samplefile.toString().split("\\.")[0].split("\\\\")[2];
        File f = new File(ArdenRecord.sadd + "/Sample Reports/" + fname + ".pdf");
        File imfile = new File(ArdenRecord.sadd + "/logo.png");

        PDImageXObject pdImage = PDImageXObject.createFromFile(imfile.toString(), document);

        PDPageContentStream contents = new PDPageContentStream(document, page);
        PDRectangle mediaBox = page.getMediaBox();

        float startX = (mediaBox.getWidth() - pdImage.getWidth()) / 2;
        float startY = (mediaBox.getHeight() - pdImage.getHeight()) / 2;
        contents.drawImage(pdImage, startX, startY);

        contents.beginText();
        contents.newLineAtOffset(25, 700);
        contents.setFont(PDType1Font.TIMES_ROMAN, 12);
        BufferedReader br = new BufferedReader(new FileReader(samplefile));

        String st;
        int n = 0;
        while ((st = br.readLine()) != null) {
            if (n < 4 || n > 20 && n < 30) {
                contents.showText(st);
                contents.newLineAtOffset(0, -18);
            }
            n++;
        }

        contents.endText();
        contents.close();

        document.save(f);
        document.close();

        Desktop.getDesktop().open(f);
    }


}```

Upvotes: 0

Views: 1122

Answers (1)

haba713
haba713

Reputation: 2677

Maybe there's nothing wrong with your code. I copy-pasted (removed .split("\\\\")[2] to get path right), compiled and tested it with PDFBox 2.0.17, OpenJDK 8, this PNG file and the first chapter of Lorem Ipsum in a text file. See the result below (Adobe Reader screenshot).

enter image description here

At least you should try with a different PNG file.

Upvotes: 1

Related Questions