pdf多文件合并

【第三方工具】点我传送:https://www.ilovepdf.com/

【java功能实现】

导入jar包

javascript 复制代码
<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.13.4</version>
        </dependency>

代码

javascript 复制代码
package com.czh.pdf_spring;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfReader;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.*;

@SpringBootTest
class PdfSpringApplicationTests {
    /**
     * 指定文件夹
     * @throws FileNotFoundException
     */
    @Test
    void test() throws IOException, DocumentException {
        //pdf文件夹
        String path = "D:/pdf";
        //绝对路径
        String outputPdf = "D:/test_pdf.pdf";
        //获取文件夹下的所有文件
        File[] files = new File(path).listFiles();
        if(files != null){
            //创建文档
            Document document = new Document();
            //文档名称
            PdfCopy copy = new PdfCopy(document, new FileOutputStream(outputPdf));
            //打开文档
            document.open();
            //写入类容
            for (File file : files) {
                //创建输入流
                FileInputStream inputStream = new FileInputStream(file);
                PdfReader reader = new PdfReader(inputStream);
                    for (int i = 1; i <= reader.getNumberOfPages(); i++) {
                        document.newPage();
                        copy.addPage(copy.getImportedPage(reader, i));
                    }
                reader.close();
                inputStream.close();
            }
            //关闭文档
            document.close();
        }
        System.out.println("pdf file successfully!");
    }
}

由于朋友工作需要,所以帮了下忙,链接作者是指定的文件名,朋友的pdf文件巨多,不方便,所以改成了指定文件夹的方式,

参考链接:https://blog.csdn.net/yuchenff/article/details/143170405

相关推荐
Rain的Java大神之路14 小时前
前端转 Java 全栈:用 AI 两天交付一个能跑的 Demo,踩坑全记录
java·前端·后端
蜡笔小谢1 天前
DeepSeek Harness Java 实战笔记(五)|插件、MCP 与 Skill
java·笔记·ai·agent·deepseek·harness
唐老板1 天前
Spring AI 2.0 只支持 Boot 4
java
琳少_1 天前
java程序设计笔记
java·开发语言·数据库·笔记
小荷才露尖尖角,早有蜻蜓立上头1 天前
SpringBoot 定时任务
java·spring boot·后端
Helix2501 天前
JDK高频报错速查手册:javac不是内部命令、内存溢出、版本不兼容等12类问题解决方法
java·开发语言·内存溢出·java异常处理·jdk版本兼容·jdk报错·javac报错
CoderYanger1 天前
A.每日一题:2243. 计算字符串的数字和
java·开发语言·程序人生·leetcode·面试·蓝桥杯·学习方法
摇滚侠1 天前
《On Java 中文版 基础卷》阅读笔记 接口 19
java·开发语言·笔记
吃我一窝jio1 天前
Java多线程核心知识点梳理
java·开发语言·笔记
这个昵称不容易1 天前
在线考试系统设计与实现:14 张表 158 个接口,组卷、答题、判分一条线走通
java·springboot·毕设