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

Draw Image with Background color using PDF BOX library

使用下面的代码,我可以创建一个带有图像的 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();

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