无法使用PDFBox将图像添加到pdf [英] Can't add an image to a pdf using PDFBox

查看:210
本文介绍了无法使用PDFBox将图像添加到pdf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个使用pdfbox库从头开始创建pdf的java应用程序。

我需要在页面中放置一个jpg图像。

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.

我正在使用此代码:

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

当我运行代码时,它会成功终止,但如果我使用Acrobat Reader打开生成的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.

任何提示如何将我的图像放在pdf中?

Any hint on how to put my image in the pdf?

推荐答案

绝对将页面添加到文档中。你会想要这样做,但我也注意到如果你在PDJpeg之前创建PDPageContentStream,PDFBox将不会写出图像。没有解释为什么会这样,但如果你仔细观察ImageToPDF的来源,那就是他们所做的。在PDJpeg之后创建PDPageContentStream并且它神奇地工作。

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

这篇关于无法使用PDFBox将图像添加到pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆