使用Java将多个PDF合并为一个PDF

public static byte[] mix(List<byte[]> bytes) throws Exception {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        Document document = new Document();// 创建一个新的PDF
        PdfCopy copy = new PdfCopy(document, bos);
        document.open();
        for (byte[] bs : bytes) {// 取出单个PDF的数据
            PdfReader reader = new PdfReader(bs);
            int pageTotal= reader.getNumberOfPages();
            log.info("pdf的页码数是 ==> {}",pageTotal);
            for (int pageNo=1;pageNo<=pageTotal;pageNo++){
                document.newPage();
                PdfImportedPage page = copy.getImportedPage(reader, pageNo);
                copy.addPage(page);
            }
            reader.close();
        }
        document.close();
        byte[] pdfs = bos.toByteArray();
        bos.close();
        copy.close();
        return pdfs;
    }

工具包使用的itextPDF

<dependency>
   <groupId>com.itextpdf</groupId>
   <artifactId>itextpdf</artifactId>
   <version>5.4.3</version>
</dependency>
  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
Java中,iText一个流行的库,用于处理PDF文档。如果你想要合并多个PDF文件到一个新的PDF中,可以使用iText提供的`PdfCopy`, `Document`, 和 `PdfStamper` 等类。以下是一个简单的步骤示例: ```java import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.pdf.PdfCopy; import com.itextpdf.text.pdf.PdfReader; import java.io.FileOutputStream; import java.io.IOException; public class PdfMerger { public static void main(String[] args) { try { // 创建一个目标文档 Document document = new Document(); // 指定输出流 FileOutputStream fos = new FileOutputStream("merged.pdf"); // 读取每个源PDF文件 for (String sourceFile : getSourceFiles()) { PdfReader reader = new PdfReader(sourceFile); // 使用PdfCopy将内容复制到新的PDFPdfCopy copy = new PdfCopy(document, fos); document.open(); // 打开文档 copy.copyPage(reader, 1); // 复制第一页 reader.close(); // 关闭源PDF // 如果还有更多页,循环处理 int n = reader.getNumberOfPages(); while (copy.getCurrentPageNumber() < n) { copy.copyPage(reader, ++copy.getCurrentPageNumber()); } } // 关闭并提交文档 document.close(); fos.close(); System.out.println("PDF合并完成!"); } catch (DocumentException | IOException e) { e.printStackTrace(); } } private static String[] getSourceFiles() { // 这里替换为实际的源PDF文件列表 // ... return new String[]{"file1.pdf", "file2.pdf", "file3.pdf"}; } } ``` 在这个例子中,你需要先创建一个`Document`对象,然后遍历源PDF文件列表,对每份文件创建一个`PdfReader`,使用`PdfCopy`将内容逐页添加到新文档中。最后关闭所有资源。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值