2017-07-19 131 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告訴它的圖形狀態下讓您流的開始復位。

此外,你不真的使用第二個內容流...

相關問題