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);
    }
}
相关推荐
挖掘狂人3 分钟前
同一个端口能不能被两个程序同时监听?
java·后端·程序员
codigger7 分钟前
同一个端口能不能被两个程序同时监听?
java·后端·程序员·编程
西索斯coding7 分钟前
qwen3.8-max-0902 和 minimax-m3 改真实仓库差多少?2026 年 50 个缺陷复现实测框架
java·服务器·网络·ai
优化控制仿真模型11 分钟前
2026【英一】考研英语一历年真题及答案解析PDF电子版(1980-2025年)
考研·pdf
2501_9339232515 分钟前
SpringCloud:OpenFeign快速实现
java·后端·spring cloud·openfeign
m0_7381207220 分钟前
JWT 安全从入门到实战:六种典型攻击场景解析
前端·网络·python·安全·网络安全
用户2986985301422 分钟前
Python 实现 HTML 转纯文本:两种场景下的文档模型方案
python·html·api
denlaku23 分钟前
JDK 26 新特性详解
java
SL_staff27 分钟前
3分钟完成业务规则调整:告别代码修改,实现拖拽式逻辑配置
java·低代码·全栈
Flynn Liang32 分钟前
让 AI 查订单、查库存、发消息:Spring AI 自定义工具(Tool)实战与工具描述工程
java·人工智能·spring·函数调用·springai·tool·自定义工具