优化使用 itext 合并多个 pdf 方案,解决使用 Itext 合并 pdf 报错 PDF header signature not found

文章讲述了作者在使用iText库合并PDF时遇到的`PDFheadersignaturenotfound`问题,以及后续对代码进行的分析,包括解决文件占用、流关闭等问题,优化了处理速度和资源管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

1、原文链接:

2、代码分析

3、解决问题

4、使用扩展


1、原文链接:

(已解决)使用Itext合并pdf报错:com.itextpdf.text.exceptions.InvalidPdfException: PDF header signature not found_小庆_007的博客-CSDN博客

 

2、代码分析

这是我上篇关于 itext 的代码,已经解决了 PDF header signature not found 这个问题。后面分析了一下还是存在很多问题。例如:手动删除文件时被占用,PdfReader 对象循环创建没有完全关闭。FileOutputStream 流没有正确关闭。将文件全部加载到内存中处理速度过快,导致影响 wkhtmltopdf 工具线程还没处理完,主线程就已经跑完了导致的 IO 异常等等

package com.lxq.utils;
 
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
 
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
 
public class PdfUtil {
 
    /**
     * author luXiaoQing
     * @param filePaths      需要拼接的多个pdf文件路径
     * @param outputFilePath 合并后pdf输出路径
     * @param outputFileName 合并后pdf文件名
     */
    public static void mergePdf(List<String> filePaths, String outputFilePath, String outputFileName) {
        if (filePaths.isEmpty()) {
            return;
        }
        if (!Utils.checkNotNull(outputFilePath) || !Utils.checkNotNull(outputFileName)) {
            return;
        }
 
        Document document = null;
        PdfCopy copy = null;
        PdfReader reader = null;
        try {
            List<byte[]> fileBytes = new ArrayList<byte[]>();
            for (String filePath : filePaths) {
                fileBytes.add(Files.readAllBytes(Paths.get(filePath)));
            }
            document = new Document(new PdfReader(filePaths.get(0)).getPageSize(1));
            copy = new PdfCopy(document, new FileOutputStream(outputFilePath + outputFileName));
            document.open();
            for (byte[] fileByte : fileBytes) {
                reader = new PdfReader(fileByte);
                int numberOfPage = reader.getNumberOfPages();
                //注意 i 从 1 开始
                for (int i = 1; i <= numberOfPage; i++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, i);
                    copy.addPage(page);
                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage() + e);
        } finally {
            if (Utils.checkNotNull(document)) {
                document.close();
            }
            if (Utils.checkNotNull(reader)) {
                reader.close();
            }
            if (Utils.checkNotNull(copy)) {
                copy.close();
            }
        }
    }
}

3、解决问题
package com.lxq.utils;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

public class PdfUtil {

    /**
     * author luXiaoQing
     * @param filePaths      需要拼接的多个pdf文件路径
     * @param outputFilePath 合并后pdf输出路径
     * @param outputFileName 合并后pdf文件名
     */
    public static void mergePdf(List<String> filePaths, String outputFilePath, String outputFileName) {
        if (filePaths.isEmpty()) {
            return;
        }
        if (!Utils.checkNotNull(outputFilePath) || !Utils.checkNotNull(outputFileName)) {
            return;
        }

        Document document = null;
        PdfCopy copy = null;
        FileOutputStream fos = null;
        File outputFile = new File(outputFilePath + outputFileName);

        try {
            fos = new FileOutputStream(outputFile);
            for (String filePath : filePaths) {
                File pdf = new File(filePath);
                if (!pdf.exists()) {
                    throw new IOException("文件" + filePath + "不存在");
                }
                PdfReader reader = null;
                
                try {
                    reader = new PdfReader(filePath);
                    if (document == null) {
                        //使用第1页的尺寸
                        document = new Document(reader.getPageSize(1));
                        copy = new PdfCopy(document, fos);
                        document.open();
                    }
                    int numberOfPage = reader.getNumberOfPages();
                    //for循环从1开始
                    for (int i = 1; i <= numberOfPage; i++) {
                        document.newPage();
                        assert copy != null;
                        PdfImportedPage page = copy.getImportedPage(reader, i);
                        copy.addPage(page);
                    }
                } catch (Exception e) {
                    System.out.println(e.getMessage() + e);
                } finally {
                    if (reader != null) {
                        reader.close();
                    }
                }
                
            }
        } catch (Exception e) {
            System.out.println(e.getMessage() + e);
        } finally {
            if (document != null) {
                document.close();
            }
            if (copy != null) {
                copy.close();
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    System.out.println(e.getMessage() + e);
                }
            }
        }
    }
}

4、使用扩展

我使用这个方法时将我的文件按顺序批量将文件路径添加到了 filePaths 集合中,其中第一个文件是主文件。要求是拼接完成后还是原文件名。所以需要在使用时多一些操作

File oldPdfFile = new File(filePath + fileName);
File newPdfFile = new File(filePath + fileName + ".tmp");
PdfUtil.mergePdf(filePaths, filePath, newPdfFile.getName());
if (!oldPdfFile.delete()) {
    throw new IOException("删除文件" + oldPdfFile.getAbsoluteFile() + "失败");
}
newPdfFile.renameTo(oldPdfFile);

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值