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);
    }
}
相关推荐
久绊A几秒前
Ubuntu及其衍生系统安装Python
开发语言·python
暗星涌动2 分钟前
Java 与设计模式(17):责任链模式
java·设计模式·责任链模式
m0_7263658323 分钟前
某宝同款百度盘不限速后台系统源码_卡密系统_Java账号管理系统部署方案
java·开发语言
奔跑吧邓邓子1 小时前
【Python爬虫(64)】从“听”开始:Python音频爬虫与语音数据处理全解析
开发语言·爬虫·python·音频·语音识别
_nut_2 小时前
手撕跳表/数据结构
java·开发语言·数据结构
没明白白2 小时前
插入排序:一种简单而直观的排序算法
java·算法·排序算法
小猪咪piggy2 小时前
【数据结构】(12) 反射、枚举、lambda 表达式
java·开发语言·数据结构
web147862107232 小时前
数据库系统架构与DBMS功能探微:现代信息时代数据管理的关键
java·开发语言·数据库
wolf犭良2 小时前
21.《SpringBoot 异步编程@Async与CompletableFuture》
java·数据库·spring
deephub2 小时前
用PyTorch从零构建 DeepSeek R1:模型架构和分步训练详解
人工智能·pytorch·python·深度学习·deepseek