(已解决)使用Itext合并pdf报错:com.itextpdf.text.exceptions.InvalidPdfException: PDF header signature not found

目录

1、问题分析

2、解决问题


本文解决方案优化方案:

优化使用 itext 合并多个 pdf 方案,解决使用 Itext 合并 pdf 报错 PDF header signature not found_小庆_007的博客-CSDN博客

1、问题分析

相关依赖:

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13</version>
</dependency>

这是我第一版没有修改前报错的代码:

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.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 {
            document = new Document(new PdfReader(filePaths.get(0)).getPageSize(1));
            copy = new PdfCopy(document, new FileOutputStream(outputFilePath + outputFileName));
            document.open();
            for (String filePath : filePaths) {
                reader = new PdfReader(filePath);
                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();
            }
        }
    }
}

报错来源:

reader = new PdfReader(filePath);

看似没问题的代码,运行起来让人头大,问题的原因也让人无语(小小吐槽一下,诶嘿~)

通过 debug 发现了问题真正的原因是下面这三行代码:

document = new Document(new PdfReader(filePaths.get(0)).getPageSize(1));
copy = new PdfCopy(document, new FileOutputStream(outputFilePath + outputFileName));
document.open();

当我执行这三行代码后,参数 filePaths 中的第一个文件大小会变成 0 KB,后面我又去循环这个 filePaths, 在第一次循环时,new PdfReader(filePath); 就会读不到正确的文件。导致报错:com.itextpdf.text.exceptions.InvalidPdfException: PDF header signature not found.

for (String filePath : filePaths) {
    reader = new PdfReader(filePath);
    int numberOfPage = reader.getNumberOfPages();
    for (int i = 1; i <= numberOfPage; i++) {
        document.newPage();
        PdfImportedPage page = copy.getImportedPage(reader, i);
        copy.addPage(page);
    }
}

2、解决问题

真正困难的其实是:发现问题发生的真正原因,上面我们已经知道了错误的原因是由于 filePaths 中的第一个文件大小是0kb,我们在循环拼接之前将 File 保存为 byte[] ,其实应该有更好的解决方式。我这里有些取巧。大家如果有更好的解决方式,可以评论或私信我。有好的解决方案大家一起分享一下。

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();
            }
        }
    }

}
### 配置 ProGuard 对 iTextPDF 进行混淆加固 对于 `com.itextpdf:itextpdf:5.5.13.4` 库进行 ProGuard 混淆加固,需要特别注意该库内部依赖关系以及对外暴露 API 的保护。以下是具体方法: #### 1. 添加必要的保持规则 为了确保 iTextPDF 功能正常运行,在 ProGuard 文件中加入如下规则来保留特定类及其成员不被混淆或移除。 ```proguard # Keep all public classes and methods that are part of the itextpdf library's API. -keep class com.itextpdf.** { *; } # Prevent obfuscation but allow shrinking for non-public members within these packages. -dontobfuscate -shrink ``` 这些设置可以防止关键组件因过度优化而失效[^1]。 #### 2. 处理资源文件路径 如果项目中有自定义字体或其他静态资源位于特殊目录下,则需通过 `-injars` 参数指定输入 JAR 包位置,并适当调整 Maven 插件配置项以适应实际环境需求。 ```xml <plugin> <groupId>com.github.wvengen</groupId> <artifactId>proguard-maven-plugin</artifactId> <!-- ... --> <configuration> <options> <option>-injars ${project.basedir}/libs/itextpdf.jar(!META-INF/MANIFEST.MF)</option> </options> </configuration> </plugin> ``` 此部分解决了类似 `<injar>${project.build.finalName}/WEB-INF/classes/</injar>` 所引发的问题[^4]。 #### 3. 调整日志级别与调试信息 为了避免不必要的警告干扰构建过程,建议降低 ProGuard 日志输出等级并关闭无关紧要的日志记录功能。 ```proguard -verysilent -dontnote ** # Suppress notes about missing classes or fields which may be used via reflection only at runtime. -printusage build/logs/proguard/seeds.txt -printmapping build/logs/proguard/mapping.txt ``` 以上措施有助于减少潜在冲突并提高处理效率[^2]。 #### 4. 测试验证 完成上述修改后,务必进行全面测试以确认应用行为未受影响。特别是针对 PDF 文档创建、编辑等功能模块执行单元测试案例集,确保其能够按预期工作。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值