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);
    }
}
相关推荐
没有bug.的程序员2 小时前
服务网格 Service Mesh:微服务通信的终极进化
java·分布式·微服务·云原生·service_mesh
Bellafu6663 小时前
selenium常用的等待有哪些?
python·selenium·测试工具
小白学大数据4 小时前
Python爬虫常见陷阱:Ajax动态生成内容的URL去重与数据拼接
爬虫·python·ajax
2401_841495645 小时前
【计算机视觉】基于复杂环境下的车牌识别
人工智能·python·算法·计算机视觉·去噪·车牌识别·字符识别
Adorable老犀牛5 小时前
阿里云-ECS实例信息统计并发送统计报告到企业微信
python·阿里云·云计算·企业微信
南尘NCA86665 小时前
企业微信防封防投诉拦截系统:从痛点解决到技术实现
java·网络·企业微信
倔强青铜三5 小时前
苦练Python第66天:文件操作终极武器!shutil模块完全指南
人工智能·python·面试
倔强青铜三5 小时前
苦练Python第65天:CPU密集型任务救星!多进程multiprocessing模块实战解析,攻破GIL限制!
人工智能·python·面试
Panda__Panda5 小时前
docker项目打包演示项目(数字排序服务)
运维·javascript·python·docker·容器·c#