Java使用itextpdf解决多个pdf文件合成一个文件,删除提示文件被占用

461 阅读1分钟

我正在参加「掘金·启航计划」

前言

最近有个加水印的需求,因为使用了免费的插件,有些限制。采用了将页数多的pdf文件进行拆分,但是使用itextpdf合并成一个文件的时候,删除有水印的文件提示文件被占用,真的很蛋Teng。

解决方法

public static void mergePdfs(List<String> pdfPaths, String outFilePath) {
    Document document = null;
    PdfReader reader1 = null;
    PdfReader reader2 = null;
    PdfCopy copy = null;
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(outFilePath);
        reader2 = new PdfReader(pdfPaths.get(0));
        document = new Document(reader2.getPageSize(1));
        copy = new PdfCopy(document, fos);
        document.open();
        for (int i = 0; i < pdfPaths.size(); i++) {
            reader1 = new PdfReader(pdfPaths.get(i));
            int n = reader1.getNumberOfPages();
            for (int j = 1; j <= n; j++) {
                document.newPage();
                PdfImportedPage page = copy.getImportedPage(reader1, j);
                copy.addPage(page);
            }
            reader1.close();
            reader1 = null;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (reader1 != null) reader1.close();
        if (reader2 != null) reader2.close();
        if (document != null) document.close();
        if (copy != null) {
            copy.flush();
            copy.close();
        }
        try {
            if (fos != null) {
                fos.flush();
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}