使用PDF BOX库绘制具有背景颜色的图像



使用以下代码,我可以创建一个带有图像的pdf文档,但我想将图像放在背景色的顶部,我尝试了一点,但无法实现。任何人都可以帮助我实现这一点:

public class SimpleTable {
public static void main(String args[]) throws Exception {
//Loading an existing document
PDDocument doc = new PDDocument();  
PDPage my_page = new PDPage();
//Retrieving the page
doc.addPage(my_page);
//Creating PDImageXObject object
PDImageXObject pdImage = PDImageXObject.createFromFile("D:\QRCode.png",doc);
//creating the PDPageContentStream object
PDPageContentStream contents = new PDPageContentStream(doc, my_page);
PDImageXObject
//Drawing the image in the PDF document
contents.drawImage(pdImage, 70, 250);
contents.setNotStrokingColoar(Color.RED);
System.out.println("Image inserted");
//Closing the PDPageContentStream object
contents.close();     
//Saving the document
doc.save("D:\QRCode.pdf");
//Closing the document
doc.close();
}

}

注:背景颜色占用率将与图像大小相同

在绘制图像之前将其放置,并删除当前代码中的填充:

contents.setNotStrokingColoar(Color.RED);
contents.addRect(70, 250, pdImage.getWidth(), pdImage.getHeight());
contents.fill();

请注意,背景颜色会使扫描二维码变得更加困难,因为对比度会降低。

最新更新