zoukankan      html  css  js  c++  java
  • pdf工具类之合并pdf文件

    实现思路:根据文件集合中第一个pdf文件新建一个pdf文件对象和文件流,将此pdf文件打开,然后循环文件及和将所有的文件按章集合顺序添加到创建的这个文件中

    这样生成的pdf文件的每一个部分,会和原pdf保持一直,即可以实现不同高宽的pdf进行合并,不会对pdf进行剪裁

    代码如下:

     1     /**
     2      * 合并原pdf为新文件
     3      *
     4      * @author 龙谷情
     5      * @date 2020/11/12 13:57
     6      * @param filePathList 文件集合
     7      * @param newFilePath 最终文件路径
     8      * @return java.io.File[返回类型说明]
     9      * @exception/throws [异常类型] [异常说明]
    10      * @since [v1.0]
    11      */
    12     public static File mergePdfFiles(List<String> filePathList, String newFilePath) {
    13         Document document = null;
    14         PdfReader pdfReader = null;
    15         FileOutputStream fileOutputStream = null;
    16         File file = null;
    17         try {
    18             pdfReader = new PdfReader(filePathList.get(0));
    19             document = new Document(pdfReader.getPageSize(1));
    20             fileOutputStream = new FileOutputStream(newFilePath);
    21             PdfCopy copy = null;
    22             copy = new PdfCopy(document, fileOutputStream);
    23             document.open();
    24             for (int i = 0; i < filePathList.size(); i++) {
    25                 PdfReader reader = new PdfReader(filePathList.get(i));
    26                 int n = reader.getNumberOfPages();
    27                 for (int j = 1; j <= n; j++) {
    28                     document.newPage();
    29                     PdfImportedPage page = copy.getImportedPage(reader, j);
    30                     copy.addPage(page);
    31                 }
    32                 reader.close();
    33             }
    34             file = new File(newFilePath);
    35         } catch (IOException e) {
    36             e.printStackTrace();
    37         } catch (DocumentException e) {
    38             e.printStackTrace();
    39         } finally {
    40             if (document != null) {
    41                 document.close();
    42             }
    43             if (pdfReader != null) {
    44                 pdfReader.close();
    45             }
    46             try {
    47                 if (fileOutputStream != null) {
    48                     fileOutputStream.close();
    49                 }
    50             } catch (IOException e) {
    51                 e.printStackTrace();
    52             }
    53         }
    54         return file;
    55     }
    昔日我曾苍老,如今风华正茂(ง •̀_•́)ง
  • 相关阅读:
    Linux下mysql的自动定时备份
    javaweb面试题
    java面试题
    Web应用优化之nginx+tomcat集群配置+redis管理session
    Web应用系统通常可以经过哪些层面的优化
    HBase安装
    博客园所有文章字数统计
    Python生成器
    Python列表生成式
    直方图均衡化-Python实现
  • 原文地址:https://www.cnblogs.com/lgqrlchinese/p/13963604.html
Copyright © 2011-2022 走看看