2017-07-19 56 views
2

我正在使用PdfBox来生成包含必须用于每个我想要生成的PDF的模板的现有PDF的PDF。无法使用PDFBox将额外内容添加到现有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(); 

    } 
+1

请包括您的代码。 – perigon

+0

由于你的问题没有说明你到底在做什么,我们只能说你做错了什么事情...... – mkl

+0

是的,我已经添加了我的代码。 –

回答

1

您创建使用此构造取代用新的任何现有的内容流的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告诉它的图形状态下让您流的开始复位。

此外,你不真的使用第二个内容流...

相关问题