简体   繁体   English

无法使用 PDFBox 将图像添加到 pdf

[英]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.我正在编写一个 Java 应用程序,它使用 pdfbox 库从头开始创建 pdf。
I need to place a jpg image in one of the page.我需要在其中一个页面中放置一个 jpg 图像。

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.当我运行代码时,它成功终止,但是如果我使用 Acrobat Reader 打开生成的 pdf 文件,页面完全是白色的,并且图像没有放置在其中。
The text instead is correctly placed in the page.而是将文本正确放置在页面中。

Any hint on how to put my image in the pdf?关于如何将我的图像放入 pdf 的任何提示?

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.你会想要这样做,但我也注意到如果你在 PDJpeg 之前创建 PDPageContentStream,PDFBox 不会写出图像。 It's unexplained why this is so, but if you look close at the source of ImageToPDF that's what they do.无法解释为什么会这样,但是如果您仔细查看 ImageToPDF 的来源,他们就是这样做的。 Create the PDPageContentStream after PDJpeg and it magically works.在 PDJpeg 之后创建 PDPageContentStream 并且它神奇地工作。

...
PDJpeg img = new PDJpeg(document, in);
PDPageContentStream stream = new PDPageContentStream( doc, page );
...

Looks like you're missing just a document.addPage(page) call.看起来您只缺少一个document.addPage(page)调用。

See also the ImageToPDF example class in PDFBox for some sample code.有关一些示例代码,另请参阅 PDFBox 中的ImageToPDF示例类。

this is how default constructor for PDPageContentStream looks like:这是PDPageContentStream 的默认构造函数的样子:

public PDPageContentStream(PDDocument document, PDPage sourcePage) throws IOException
{
    this(document, sourcePage, AppendMode.OVERWRITE, true, false);
}

Problem is AppendMode.OVERWRITE for me using another constructor with parameter PDPageContentStream.AppendMode.APPEND resolved a problem问题是 AppendMode.OVERWRITE 对我来说使用另一个带有参数PDPageContentStream.AppendMode.APPEND 的构造函数解决了一个问题

For me this worked:对我来说这有效:

PDPageContentStream contentStream =
        new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, false);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM