如何使用PDFBox将背景图像添加到PDF? [英] how to add background image to PDF using PDFBox?

查看:80
本文介绍了如何使用PDFBox将背景图像添加到PDF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using Java PDFBox version 2.0. I want to know how to add a back ground image to the pdf. I can not find any good example in the pdfbox.apache.org

推荐答案

对每个页面执行此操作,即从0到doc.getNumberOfPages():

Do this with each page, i.e. from 0 to 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对象的迭代器,构建一个List,然后在开始处插入新流,然后将此PDStream列表重新分配给setContents()的页面.如果需要,我可以将其添加为替代解决方案.

There is another way to do it which is more painful IMHO, getting a iterator of PDStream objects from the page with getContentStreams(), build a List, and insert the new stream at the beginning, and reassign this PDStream list to the page with setContents(). I can add this as an alternative solution if needed.

这篇关于如何使用PDFBox将背景图像添加到PDF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆