2013-05-29 57 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(); 
     } 
    }