2017-07-19 22 views
2

私は生成したいすべてのPdfに使用する必要があるテンプレートを含む既存のPdfを使用してPdfBoxを生成します。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 contentStream = new PDPageContentStream(document, page); 
[...] 
PDPageContentStream contents = new PDPageContentStream(document, page); 

ようPDPageContentStreamインスタンスを作成します1。最初trueストリームを圧縮するためにそれを伝え、第二trueを追加したストリームの開始時にグラフィック状態をリセットするためにそれを伝え、新しいストリームを追加するPDFBoxを伝え、ここ

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

AppendMode.APPEND:代わりに、このいずれかを使用します。

さらに、実際には2番目のコンテンツストリームを使用していません。

関連する問題