JAVA实现多个pdf文件,合并成一个pdf

package com.solar.fdd.util;

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

import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.multipdf.PDFMergerUtility;

public class PdfFileUtil {
    /**
     * pdf合并拼接
     * @Title:mulFile2One
     * @Description: TODO 
     * @date 2019年9月22日 上午10:05:37
     * @author yqwang
     * @param files 文件列表
     * @param targetPath 合并到
     * @return
     * @throws IOException
     */
    public static File mulFile2One(List files,String targetPath) throws IOException{
        // pdf合并工具类
        PDFMergerUtility mergePdf = new PDFMergerUtility();
        for (File f : files) {
            if(f.exists() && f.isFile()){
                // 循环添加要合并的pdf
                mergePdf.addSource(f);
            }
        }
        // 设置合并生成pdf文件名称
        mergePdf.setDestinationFileName(targetPath);
        // 合并pdf
        mergePdf.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
        return new File(targetPath);
    }
    
    public static void main(String[] args) throws IOException {
        List files = new ArrayList();
        files.add(new File("D:\\test\\f1.pdf"));
        files.add(new File("D:\\test\\f2.pdf"));
        files.add(new File("D:\\test\\f3.pdf"));
        File f = mulFile2One(files, "D:\\test\\mul2one.pdf");
        System.out.println(f.length());
    }
}

jar包下载地址:

https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox

https://repo1.maven.org/maven2/org/apache/pdfbox/pdfbox/2.0.17/pdfbox-2.0.17.jar

 

你可能感兴趣的:(java)