无法使用PDFBox将图像添加到pdf
我正在编写一个使用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的任何提示?
绝对将页面添加到文档中。 你会想要这样做,但我也注意到如果你在PDJpeg之前创建PDPageContentStream,PDFBox将不会写出图像。 没有解释为什么会这样,但如果你仔细观察ImageToPDF的来源,那就是他们所做的。 在PDJpeg之后创建PDPageContentStream,它神奇地起作用。
... PDJpeg img = new PDJpeg(document, in); PDPageContentStream stream = new PDPageContentStream( doc, page ); ...
看起来你只缺少一个document.addPage(page)
调用。
有关示例代码,另请参阅PDFBox中的ImageToPDF示例类。