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);
    }
}
相关推荐
全栈派森7 分钟前
云存储最佳实践
后端·python·程序人生·flask
ayiya_Oese11 分钟前
[模型部署] 1. 模型导出
图像处理·python·深度学习·神经网络·视觉检测
电商数据girl12 分钟前
酒店旅游类数据采集API接口之携程数据获取地方美食品列表 获取地方美餐馆列表 景点评论
java·大数据·开发语言·python·json·旅游
天天打码12 分钟前
python版本管理工具-pyenv轻松切换多个Python版本
开发语言·python
CircleMouse12 分钟前
基于 RedisTemplate 的分页缓存设计
java·开发语言·后端·spring·缓存
ktkiko1118 分钟前
顶层架构 - 消息集群推送方案
java·开发语言·架构
楠奕19 分钟前
python中使用neo4j
开发语言·python·neo4j
zybsjn24 分钟前
后端系统做国际化改造,生成多语言包
java·python·c#
南斯拉夫的铁托30 分钟前
labelimg安装及使用指南(yolo)
开发语言·python·yolo
不许哈哈哈44 分钟前
基于百度云ORC与阿里大语言模型的自动评分系统
python·语言模型·百度云