无法使用 PDFBox 向现有 PDF 添加额外内容

Not able to add extra content to an existing PDF using PDFBox

我正在使用 PdfBox 生成带有现有 Pdf 的 pdf,其中包含必须用于我要生成的每个 Pdf 的模板。

但是当我尝试加载 pdf 模板并想在其中写点东西时,所有以前的内容都被删除了。

所以我希望这两个内容都应该显示。

请提出任何解决方案。

这是我正在尝试执行的代码:

//Loading an existing document 
File file = new File("/home/spaneos/ScoringReports-TM-110617.pdf"); 
PDDocument document = PDDocument.load(file); 

//Retrieving the pages of the document 
PDPage page = document.getPage(0);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
//Begin the Content stream 
contentStream.beginText(); 

//Setting the font to the Content stream
contentStream.setFont( PDType1Font.TIMES_ROMAN, 16 );

//Setting the leading
contentStream.setLeading(14.5f);

//Setting the position for the line
contentStream.newLineAtOffset(25, 725);

String text1 = "This is an example of adding text to a page in the pdf document.we can add as many lines";
String text2 = "as we want like this using the ShowText()  method of the ContentStream class";

//Adding text in the form of string
contentStream.showText(text1);
contentStream.newLine();
contentStream.showText(text2);

//Creating PDImageXObject object
PDImageXObject pdImage = PDImageXObject.createFromFile("/home/spaneos/Downloads/man-161282_960_720.png",document);

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

contentStream.endText();

System.out.println("Content added");

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

//Closing the content stream
contentStream.close();

//Saving the document 
document.save(System.getProperty("user.dir").concat("/PdfBox_Examples/sample.pdf"));

//Closing the document  
document.close();

您像这样创建 PDPageContentStream 个实例

PDPageContentStream contentStream = new PDPageContentStream(document, page);
[...]
PDPageContentStream contents = new PDPageContentStream(document, page);

使用此构造函数创建它用新内容流替换任何现有内容流。而是使用这个:

PDPageContentStream contents = new PDPageContentStream(document, page, AppendMode.APPEND, true, true);

AppendMode.APPEND 告诉 PDFBox 添加新流,第一个 true 告诉它压缩流,第二个 true 告诉它重置图形状态您添加的流的开始。

此外,您并没有真正使用第二个内容流...