| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- package com.goafanti.common.utils;
- 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.List;
- /**
- * 多种文档格式合并为PDF工具类
- * 支持Word、Excel和PDF文档的合并
- */
- public class DocumentToPDFMerger{
- /**
- * 将多个PDF文件合并成一个PDF文件
- *
- * @param inputPdfPaths 输入的PDF文件路径列表
- * @param outputPdfPath 输出的PDF文件路径
- * @throws IOException
- * @throws DocumentException
- */
- public static void mergePdfFiles(List<String> inputPdfPaths, String outputPdfPath)
- throws IOException, DocumentException {
- // 创建文档和输出流
- Document document = new Document();
- FileOutputStream outputStream = new FileOutputStream(outputPdfPath);
- PdfCopy copy = new PdfCopy(document, outputStream);
- // 打开文档
- document.open();
- // 遍历所有PDF文件并合并
- for (String pdfPath : inputPdfPaths) {
- PdfReader reader = new PdfReader(pdfPath);
- // 将每个页面添加到输出文档
- for (int i = 1; i <= reader.getNumberOfPages(); i++) {
- copy.addPage(copy.getImportedPage(reader, i));
- }
- // 关闭当前PDF文件的reader以释放资源
- reader.close();
- }
- // 关闭文档和输出流
- document.close();
- outputStream.close();
- }
- /**
- * 将多个PDF文件合并成一个PDF文件(简化版)
- *
- * @param inputPdfPaths 输入的PDF文件路径数组
- * @param outputPdfPath 输出的PDF文件路径
- * @throws IOException
- * @throws DocumentException
- */
- public static void mergePdfFiles(String[] inputPdfPaths, String outputPdfPath)
- throws IOException, DocumentException {
- mergePdfFiles(java.util.Arrays.asList(inputPdfPaths), outputPdfPath);
- }
- }
|