【发布时间】:2015-10-29 05:57:02
【问题描述】:
我正在使用 Java PDFBox 2.0 版。我想知道如何在 pdf 中添加背景图像。我在 pdfbox.apache.org 中找不到任何好的示例
【问题讨论】:
我正在使用 Java PDFBox 2.0 版。我想知道如何在 pdf 中添加背景图像。我在 pdfbox.apache.org 中找不到任何好的示例
【问题讨论】:
对每一页执行此操作,即从 0 到 doc.getNumberOfPages():
PDPage pdPage = doc.getPage(page);
InputStream oldContentStream = pdPage.getContents();
byte[] ba = IOUtils.toByteArray(oldContentStream);
oldContentStream.close();
// brings a warning because a content stream already exists
PDPageContentStream newContentStream = new PDPageContentStream(doc, pdPage, false, true);
// createFromFile is the easiest way with an image file
// if you already have the image in a BufferedImage,
// call LosslessFactory.createFromImage() instead
PDImageXObject pdImage = PDImageXObject.createFromFile(imagePath, doc);
newContentStream.saveGraphicsState();
newContentStream.drawImage(pdImage, 0, 0);
newContentStream.restoreGraphicsState();
newContentStream.close();
// append the saved existing content stream
PDPageContentStream newContentStream2 = new PDPageContentStream(doc, pdPage, true, true);
newContentStream2.appendRawCommands(ba); // deprecated... needs to be rediscussed among devs
newContentStream2.close();
还有另一种更痛苦的方法,恕我直言,使用 getContentStreams() 从页面获取 PDStream 对象的迭代器,构建一个列表,并在开头插入新流,然后将此 PDStream 列表重新分配给带有 setContents() 的页面。如果需要,我可以将其添加为替代解决方案。
【讨论】:
PDPageContentStream 构造函数将流添加为第一页内容流,那就太好了。
致电PDPageContentStream.drawImage:
val document = PDDocument()
val page = PDPage()
document.addPage(page)
val contentStream = PDPageContentStream(document, page)
val imageBytes = this::class.java.getResourceAsStream("/image.jpg").readAllBytes()
val image = PDImageXObject.createFromByteArray(document, imageBytes, "background")
contentStream.drawImage(image, 0f, 0f, page.mediaBox.width, page.mediaBox.height)
contentStream.close()
page.close()
【讨论】: