Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't add an image to a pdf using PDFBox

Tags:

java

pdf

pdfbox

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?

like image 246
Davide Gualano Avatar asked Dec 15 '11 14:12

Davide Gualano


People also ask

Is PDFBox free for commercial use?

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 ...

How do you add a page to a PDFBox?

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.


1 Answers

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 ); ... 
like image 149
chubbsondubs Avatar answered Sep 24 '22 11:09

chubbsondubs