将图像插入现有的非空pdf
Insert Image to existing non-empty pdf
我正在尝试使用 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();
}
}
尝试使用append-mode
//creating the PDPageContentStream object
PDPageContentStream contents = new PDPageContentStream(doc, page, AppendMode.APPEND, true);
编辑
TilmanHausherr 提到
new PDPageContentStream(doc, page, AppendMode.APPEND, true, true);
我正在尝试使用 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();
}
}
尝试使用append-mode
//creating the PDPageContentStream object
PDPageContentStream contents = new PDPageContentStream(doc, page, AppendMode.APPEND, true);
编辑
TilmanHausherr 提到
new PDPageContentStream(doc, page, AppendMode.APPEND, true, true);