Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

java - Can't add an image to a pdf using 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...