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

时间:2011-12-15 14:01:46

标签: java pdf pdfbox

我正在编写一个使用pdfbox库从头开始创建pdf的Java应用程序 我需要将jpg图像放在其中一个页面中。

我正在使用此代码:

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文件,页面将完全为白色并且图像未放入其中。
而是将文本正确放置在页面中。

有关如何将我的图像放入pdf的任何提示?

3 个答案:

答案 0 :(得分:52)

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

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

答案 1 :(得分:6)

您似乎错过了document.addPage(page)来电。

有关示例代码,请参阅PDFBox中的ImageToPDF示例类。

答案 2 :(得分:1)

这是 PDPageContentStream 的默认构造函数的样子:

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

问题对我来说是AppendMode.OVERWRITE,使用另一个带有参数 PDPageContentStream.AppendMode.APPEND 的构造函数解决了问题

这对我来说很有效:

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