2013-05-29 54 views
2

我使用下面的代碼合併兩個PDF文件:如何在合併兩個pdf時將頁碼添加到輸出pdf中?

File firstPdfFile = new File("firstPdf.pdf"); 
File secondPdfFile = new File("secondPdf.pdf"); 
PDFMergerUtility merger = new PDFMergerUtility(); 
merger.addSource(firstPdfFile);  
merger.addSource(secondPdfFile); 
String pdfPath = "PdfFile.pdf"; 
OutputStream bout2 = new BufferedOutputStream(new FileOutputStream(pdfPath)); 
merger.setDestinationStream(bout2); 
merger.mergeDocuments();  
File pdfFile = new File(pdfPath); 

我正確地得到合併的PDF,但我想添加這個PDF文件頁碼。

+0

如果你想在第二遍中做到這一點,請看[這個答案*使用PDFBox *添加頁碼](http://stackoverflow.com/a/16585032/1729265)。如果您想一次完成,您必須將該解決方案與[PDFMergerUtility.java](http://svn.apache.org/repos/asf/pdfbox/trunk/pdfbox/src/main/java /org/apache/pdfbox/util/PDFMergerUtility.java)。 – mkl

+0

如果我這樣做,我錯誤地得到頁碼。 對於例如: 如果firstpdf.pdf內容有2頁意味着頁碼顯示1 2,2 2這樣的.. 和secondpdf.pdf有3頁意味着頁碼再次1 0f 3,2的3,就像那樣.. – Mathi

+1

在這種情況下,使用鏈接的示例將頁碼分別添加到源PDF,然後合併增強源PDF。我想也不難。 – mkl

回答

1

試試看看這個代碼。

File firstPdfFile = new File("firstPdf.pdf"); 
    File secondPdfFile = new File("firstPdf.pdf"); 
    PDFMergerUtility merger = new PDFMergerUtility(); 
    merger.addSource(firstPdfFile); 
    merger.addSource(secondPdfFile); 
    String pdfPath = "PdfFile.pdf"; 
    OutputStream bout2 = new BufferedOutputStream(new FileOutputStream(pdfPath)); 
    merger.setDestinationStream(bout2); 
    merger.mergeDocuments(); 

    PDDocument doc = null; 
    try { 
     URL file = new URL("file:///PdfFile.pdf"); 
     doc = PDDocument.load(file); 

     List<?> allPages = doc.getDocumentCatalog().getAllPages(); 
     PDFont font = PDType1Font.HELVETICA_BOLD; 
     float fontSize = 36.0f; 
     for (int i = 0; i < allPages.size(); i++) { 
      PDPage page = (PDPage) allPages.get(i); 
      PDPageContentStream footercontentStream = new PDPageContentStream(doc, page, true, true); 
      footercontentStream.beginText(); 
      footercontentStream.setFont(font, fontSize); 
      footercontentStream.moveTextPositionByAmount((PDPage.PAGE_SIZE_A4.getUpperRightX()/2), (PDPage.PAGE_SIZE_A4.getLowerLeftY())); 
      footercontentStream.drawString(String.valueOf(i + 1)); 
      footercontentStream.endText(); 
      footercontentStream.close(); 
     } 
     doc.save("PdfFile.pdf"); 
    } finally { 
     if (doc != null) { 
      doc.close(); 
     } 
    }