如何使用PDFBox将背景图像添加到PDF?

时间:2015-10-29 05:57:02

标签: java pdfbox

我正在使用Java PDFBox 2.0版。我想知道如何将背景图像添加到pdf中。我在pdfbox.apache.org

中找不到任何好的例子

2 个答案:

答案 0 :(得分:1)

对每个页面执行此操作,即从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();           

还有另一种方法可以做到这一点,这是更痛苦的恕我直言,从页面获取PDStream对象的迭代器与getContentStreams(),构建一个List,并在开头插入新流,并将此PDStream列表重新分配给setContents()的页面。如果需要,我可以将其添加为替代解决方案。

答案 1 :(得分:0)

致电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()