zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Java当中多个pdf文件合并为一个

JAVA文件PDF 一个 多个 合并 当中
2023-09-11 14:15:14 时间

这里合并用到了一个itext的包。使用maven直接导入依赖即可。

<dependency>
    <groupId>com.lowagie</groupId>
    <artifactId>itext</artifactId>
    <version>2.1.7</version>
</dependency>

这个是我写的一个utl工具类,里面还写了一个main方法,如果你有两个pdf,可以直接用main方法跑一下。

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

import java.io.FileOutputStream;

public class PdfUtil {

    /**
     * 合并pdf
     * @param files 需要合并的pdf路径
     * @param newfile 合并成新的文件的路径
     * @return
     */
    public static boolean mergePdfFiles(String[] files, String newfile) {
        boolean retValue = false;
        Document document = null;
        PdfCopy copy = null;
        PdfReader reader = null;
        try {
            document = new Document(new PdfReader(files[0]).getPageSize(1));
            copy = new PdfCopy(document, new FileOutputStream(newfile));
            document.open();
            for (int i = 0; i < files.length; i++) {
                reader = new PdfReader(files[i]);
                int n = reader.getNumberOfPages();
                for (int j = 1; j <= n; j++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, j);
                    copy.addPage(page);
                }
            }
            retValue = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (copy != null) {
                copy.close();
            }
            if (document != null) {
                document.close();
            }
        }
        return retValue;
    }

    public static void main(String[] args) {
        String[] files = { "D:\\Case\\0000001\\00001\\ABIStatistic.pdf", "D:\\Case\\0000001\\00001\\ABITable.pdf",
                "D:\\Case\\0000001\\00001\\CVRR.pdf" };
        String savepath = "D:\\Case\\0000001\\00001\\temp.pdf";
        boolean b = mergePdfFiles(files, savepath);
        System.out.println(b);
    }
}