+-
如何使用PDFBox将背景图像添加到PDF?
我正在使用 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();           

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

点击查看更多相关文章

转载注明原文:如何使用PDFBox将背景图像添加到PDF? - 乐贴网