21xrx.com
2025-03-25 11:14:41 Tuesday
文章检索 我的文章 写文章
Java实现PDF文件合并,代码案例详解
2023-06-16 19:10:14 深夜i     18     0
Java PDF 合并

PDF文件的合并功能一直都是很常见的需求,今天我们就来说一下如何用Java实现PDF文件的合并。通过本文,你将了解到以下内容:

1.如何使用iText库解析PDF文件。

2.如何在Java中使用iText库进行PDF文件合并。

3.如何批量合并PDF文件。

示例代码如下:

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MergePDF {
  public static void main(String[] args) throws IOException, DocumentException {
    String[] pdfs = "file2.pdf"; //要合并的文件名
    String output = "merged.pdf"; //输出文件名
    List
  readers = new ArrayList<>();
 
    for (String pdf : pdfs) {
      readers.add(new PdfReader(pdf));
    }
    Document document = new Document();
    PdfCopy copy = new PdfCopy(document, new FileOutputStream(output));
    document.open();
    for (PdfReader reader : readers) {
      for (int i = 1; i <= reader.getNumberOfPages(); i++) {
        copy.addPage(copy.getImportedPage(reader, i));
      }
    }
    document.close();
    System.out.println("合并完成!");
  }
}

  
  

评论区