I'm writing a java app that creates a pdf from scratch using the pdfbox library.
I need to place a jpg image in one of the page.
I'm using this code:
PDDocument document = new PDDocument(); PDPage page = new PDPage(PDPage.PAGE_SIZE_A4); document.addPage(page); PDPageContentStream contentStream = new PDPageContentStream(document, page); /* ... */ /* code to add some text to the page */ /* ... */ InputStream in = new FileInputStream(new File("c:/myimg.jpg")); PDJpeg img = new PDJpeg(document, in); contentStream.drawImage(img, 100, 700); contentStream.close(); document.save("c:/mydoc.pdf");
When I run the code, it terminates successfully, but if I open the generated pdf file using Acrobat Reader, the page is completely white and the image is not placed in it.
The text instead is correctly placed in the page.
Any hint on how to put my image in the pdf?
Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative ...
You can add a page to the PDF document using the addPage() method of the PDDocument class. To this method you need to pass the PDPage object as a parameter. Therefore, add the blank page created in the previous step to the PDDocument object as shown in the following code block. document.
Definitely add the page to the document. You'll want to do that, but I've also noticed that PDFBox won't write out the image if you create the PDPageContentStream BEFORE the PDJpeg. It's unexplained why this is so, but if you look close at the source of ImageToPDF that's what they do. Create the PDPageContentStream after PDJpeg and it magically works.
... PDJpeg img = new PDJpeg(document, in); PDPageContentStream stream = new PDPageContentStream( doc, page ); ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With