如何使用Java合并两个PDF。(How to merge two PDFs using Java.)

优质
小牛编辑
129浏览
2023-12-01

问题描述 (Problem Description)

如何使用Java合并两个PDF。

解决方案 (Solution)

以下是使用Java合并两个pdf文档的示例程序。

import org.apache.pdfbox.multipdf.PDFMergerUtility; 
import org.apache.pdfbox.pdmodel.PDDocument;  
import java.io.File; 
import java.io.IOException;  
public class MergingPdfs { 
   public static void main(String[] args) throws IOException { 
      //Loading an existing PDF document 
      File file1 = new File("C:/pdfBox/sample1.pdf"); 
      PDDocument doc1 = PDDocument.load(file1); 
      File file2 = new File("C:/pdfBox/sample2.pdf"); 
      PDDocument doc2 = PDDocument.load(file2); 
      //Instantiating PDFMergerUtility class 
      PDFMergerUtility PDFmerger = new PDFMergerUtility();       
      //Setting the destination file 
      PDFmerger.setDestinationFileName("C:/pdfBox/merged.pdf"); 
      //adding the source files 
      PDFmerger.addSource(file1); 
      PDFmerger.addSource(file2); 
      //Merging the two documents 
      PDFmerger.mergeDocuments(); 
      System.out.println("Documents merged"); 
      //Closing the documents 
      doc1.close(); 
      doc2.close();           
   } 
}