使用itextpdf 实现PDF合并

本文介绍了iTextPDF库,一个强大的Java库,可用于创建、编辑PDF文档,包括合并PDF、添加水印和处理字体等。文章详细讲解了如何引入相关jar包,并提供了实际的代码示例,展示了如何使用iTextPDF进行PDF文件操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文章目录


前言

iTextPDF是一个用于处理PDF文档的Java库。它提供了一套强大的API,可以创建、编辑和操作PDF文档。iTextPDF可以用于生成PDF报告、填充PDF表单、添加水印、合并和拆分PDF文件等。它还支持字体嵌入、表格、图像和多种文本格式。iTextPDF是一个开源库,可以免费使用,同时也有商业版提供更多功能和支持。它被广泛应用于企业应用、电子商务、、教育、金融等领域

使用步骤 

  • 引入iText相关jar包

<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itextpdf</artifactId>
        <version>5.5.13</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.itextpdf/itext-asian -->
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itext-asian</artifactId>
        <version>5.2.0</version>
    </dependency>
<!--     https://mvnrepository.com/artifact/com.itextpdf.tool/xmlworker -->
    <dependency>
        <groupId>com.itextpdf.tool</groupId>
        <artifactId>xmlworker</artifactId>
        <version>5.5.13</version>
    </dependency> 

  • 相关代码示例

  •  Util类

import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;

import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author: youchao
 * @description:
 * @data: 2024/1/22 15:46
 **/
public class PdfUtils {
   

public static Document createDocument(HttpServletResponse response, String fileName) {
        try {
            response.reset();
            response.setHeader("Content-Type", "application/pdf-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 设置大小
        return new Document(PageSize.A4, 50, 50, 80, 50);
    }

   

public static void mergePdf(Document document, List<byte[]> byteList, String path) {
        try {
            FileOutputStream os = new FileOutputStream(path);

            // 以任意一个页面创建pdf模板
            document = new Document(PageSize.A4);

            PdfCopy copy = new PdfCopy(document, os);

            // 打开文档
            document.open();
            // 遍历pdf文件
            for (byte[] bytes : byteList) {
                // 读取pdf
                PdfReader reader = new PdfReader(bytes);

                // 获取页数
                int numberOfPages = reader.getNumberOfPages();
                // 从第一页开始
                for (int i = 1; i <= numberOfPages; i++) {
                    // 新建文档页
                    document.newPage();
                    // 复制操作
                    PdfImportedPage page = copy.getImportedPage(reader, i);
                    copy.addPage(page);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("PDF合并失败!");
        } finally {
            if (document != null) {
                document.close();
            }
        }
    }
}

 private byte[] inputStreamToByte(InputStream inputStream) {
        try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes)) != -1) {
                os.write(bytes, 0, len);
            }
            os.flush();
            return os.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException("InputStream转换失败!");
        }
    } 

  • 业务代码示例 

  public String margeAll() throws Exception {

        // 加载本地文件 将需要合并的PDF文件放入集合中
        List<String> paths = new ArrayList<>();  

        FileInputStream inputStream = null;

        

        //将合并后的PDF所存在的路径 可以根据业务需求转化为输出流等等
        String pdfPath = null;

        try {
            // 判断文件是否合规、以及转化为输入流
            List<byte[]> byteList = new ArrayList<>();
            for (String path : paths) {
                File file = new File(path);
                // 限制格式只能为pdf
                if (!file.exists()) {
                    throw new RuntimeException("文件不存在!");
                }
                if (file.length() <= 0) {
                    throw new RuntimeException("文件不能为空!");
                }

                String name = file.getName();
                String substring = name.substring(name.lastIndexOf(".") + 1);
                if (!substring.equals("pdf")) {
                    throw new RuntimeException("只能上传pdf格式文件!");
                }

                // 获取输入流
                inputStream = new FileInputStream(file);
                byte[] bytes = inputStreamToByte(inputStream);
                byteList.add(bytes);
            }

           

             // 1.设置输出流名称 纸张大小
            Document document = new Document(PageSize.A4);

    

            // 2.开启合并
            PdfUtils.mergePdf(document, byteList, pdfPath);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
        return pdfPath;
    }

总结

        以上即是使用itextpdf 实现PDF合并简单实例代码 希望可以帮助到大家!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AKYChao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值