DocumentToPDFMerger.java 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package com.goafanti.common.utils;
  2. import com.itextpdf.text.Document;
  3. import com.itextpdf.text.DocumentException;
  4. import com.itextpdf.text.pdf.PdfCopy;
  5. import com.itextpdf.text.pdf.PdfReader;
  6. import java.io.FileOutputStream;
  7. import java.io.IOException;
  8. import java.util.List;
  9. /**
  10. * 多种文档格式合并为PDF工具类
  11. * 支持Word、Excel和PDF文档的合并
  12. */
  13. public class DocumentToPDFMerger{
  14. /**
  15. * 将多个PDF文件合并成一个PDF文件
  16. *
  17. * @param inputPdfPaths 输入的PDF文件路径列表
  18. * @param outputPdfPath 输出的PDF文件路径
  19. * @throws IOException
  20. * @throws DocumentException
  21. */
  22. public static void mergePdfFiles(List<String> inputPdfPaths, String outputPdfPath)
  23. throws IOException, DocumentException {
  24. // 创建文档和输出流
  25. Document document = new Document();
  26. FileOutputStream outputStream = new FileOutputStream(outputPdfPath);
  27. PdfCopy copy = new PdfCopy(document, outputStream);
  28. // 打开文档
  29. document.open();
  30. // 遍历所有PDF文件并合并
  31. for (String pdfPath : inputPdfPaths) {
  32. PdfReader reader = new PdfReader(pdfPath);
  33. // 将每个页面添加到输出文档
  34. for (int i = 1; i <= reader.getNumberOfPages(); i++) {
  35. copy.addPage(copy.getImportedPage(reader, i));
  36. }
  37. // 关闭当前PDF文件的reader以释放资源
  38. reader.close();
  39. }
  40. // 关闭文档和输出流
  41. document.close();
  42. outputStream.close();
  43. }
  44. /**
  45. * 将多个PDF文件合并成一个PDF文件(简化版)
  46. *
  47. * @param inputPdfPaths 输入的PDF文件路径数组
  48. * @param outputPdfPath 输出的PDF文件路径
  49. * @throws IOException
  50. * @throws DocumentException
  51. */
  52. public static void mergePdfFiles(String[] inputPdfPaths, String outputPdfPath)
  53. throws IOException, DocumentException {
  54. mergePdfFiles(java.util.Arrays.asList(inputPdfPaths), outputPdfPath);
  55. }
  56. }