java合成多个pdf为一个pdf

pom文件

java 复制代码
      <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext</artifactId>
            <version>2.1.7</version>
        </dependency>

主文件

java 复制代码
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 合并成新的文件的路径
     */
    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);
                }
				reader.close();
            }
            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 = {"C:\\Users\\bdc1.pdf","C:\\Users\\bdc2.pdf" ,"C:\\Users\\bdc3.pdf"};
        //合并后的文件
        String savepath = "C:\\Users\\bdc0.pdf";
        boolean b = mergePdfFiles(files, savepath);
        System.out.println(b);
    }
}
相关推荐
Python开发吖23 分钟前
【已解决】python的kafka-python包连接kafka报认证失败
开发语言·python·kafka
aini_lovee3 小时前
python在容器内克隆拉取git私有仓库
git·python·elasticsearch
编程乐学(Arfan开发工程师)5 小时前
56、原生组件注入-原生注解与Spring方式注入
java·前端·后端·spring·tensorflow·bug·lua
安全系统学习5 小时前
网络安全之RCE简单分析
开发语言·python·算法·安全·web安全
周某某~6 小时前
七.适配器模式
java·设计模式·适配器模式
蹦蹦跳跳真可爱5897 小时前
Python----神经网络发(神经网络发展历程)
人工智能·python·深度学习·神经网络·计算机视觉
奔跑的小十一7 小时前
JDBC接口开发指南
java·数据库
刘大猫.7 小时前
业务:资产管理功能
java·资产管理·资产·资产统计·fau·bpb·mcb
chao_7897 小时前
标注工具核心代码解析——class AnnotationVie【canvas.py]
开发语言·python·qt5
YuTaoShao7 小时前
Java八股文——JVM「内存模型篇」
java·开发语言·jvm