将图像插入现有的非空 pdf

Raj*_*Raj 2 java pdf image pdfbox

我正在尝试使用 apache PDFBOX 将图像保存到现有的 pdf 中,但我的内容被删除,当我将图像放在 pdf 上时,我得到空白文档,有解决问题的方法吗?

我的代码看起来像这样。

    public class TestPdfImage {
        public static void main(String args[]) throws Exception {
              //Loading an existing document
              File file = new File("...../mydoc.pdf");
              PDDocument doc = PDDocument.load(file);

              //Retrieving the page
              PDPage page = doc.getPage(0);

              //Creating PDImageXObject object
              PDImageXObject pdImage = PDImageXObject.createFromFile("...../sample.png",doc);

              //creating the PDPageContentStream object
              PDPageContentStream contents = new PDPageContentStream(doc, page);

              //Drawing the image in the PDF document
              contents.drawImage(pdImage, 70, 250);

              System.out.println("Image inserted");

              //Closing the PDPageContentStream object
              contents.close();     

              //Saving the document
              doc.save(".../sample.pdf");

              //Closing the document
              doc.close();

           }

    }
Run Code Online (Sandbox Code Playgroud)

Wul*_*ulf 5

尝试使用追加模式

//creating the PDPageContentStream object
PDPageContentStream contents = new PDPageContentStream(doc, page, AppendMode.APPEND, true);
Run Code Online (Sandbox Code Playgroud)

编辑

蒂尔曼豪舍尔提到

new PDPageContentStream(doc, page, AppendMode.APPEND, true, true);
Run Code Online (Sandbox Code Playgroud)

这就是为什么

  • 他应该使用五参数构造函数。 (3认同)