Java 中将多个 PDF 文件合并为一个 PDF

一.前言

我们将从以下两个方面向您展示如何将多个PDF文件合并为一个PDF:
1. 将文件中的多个 PDF 合并为单个 PDF
2. 将流中的多个 PDF 合并为单个 PDF

1. 了解 Spire.PDF 库

要在 Java 中合并 PDF 文件,我们将使用Spire.PDF 库。Spire.PDF for Java 是一个 PDF API,使 Java 应用程序能够在不使用 Adob​​e Acrobat 的情况下读取、写入和保存 PDF 文档。它提供了用于操作 PDF 文件的广泛功能,包括将多个 PDF 文件合并到单个文档中。

在我们使用 Spire.PDF 合并 PDF 文件之前,我们需要将其依赖项添加到我们的 Java 项目中。我们可以通过向 Maven 项目添加以下依赖项来实现此目的:

xml 复制代码
<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>

<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>9.5.6</version>
    </dependency>
</dependencies>

2.将文件中的多个 PDF 合并为单个 PDF

  1. 获取要合并的文档的路径并将其存储在 String 数组中。
  2. 使用PdfDocument.mergeFiles()方法合并选定的 PDF 文件。
  3. 使用PdfDocumentBase.save()方法保存 PDF 文档。
java 复制代码
import com.spire.pdf.*;

public class mergePDF {

    public static void main(String[] args) throws Exception {

        //Get the paths of the documents to be merged
        String[] files = new String[] {
                "D:\\sample.pdf",
                "D:\\sample1.pdf"};

        //Merge documents and return an object of PdfDocumentBase
        PdfDocumentBase pdf = PdfDocument.mergeFiles(files);

        //Save the result to a PDF file
        pdf.save("MergedPDF.pdf", FileFormat.PDF);

    }
}

3.将流中的多个 PDF 合并为单个 PDF

从流中加载 PDF 并将其合并为新的 PDF 是处理多个 PDF 文档而无需将它们保存到磁盘的便捷有效的方法。当处理您不想存储在本地驱动器上的大型或敏感文件时,此方法特别有用。Spire.PDF还支持从流中加载PDF,然后将它们组合成一个新的PDF文件。

  1. 获取 PDF 流的路径,然后将它们存储到FileInputStream数组中。
  2. 使用PdfDocument.mergeFiles()方法合并选定的 PDF 文件。
  3. 使用PdfDocumentBase.save()方法保存 PDF 文档。
java 复制代码
import com.spire.pdf.*;
import java.io.*;

public class mergePDFbyStream {

    public static void main(String[] args) throws Exception {

        FileInputStream stream1 = new FileInputStream(new File("sample.pdf"));
        FileInputStream stream2 = new FileInputStream(new File("sample1.pdf"));

        InputStream[] streams = new FileInputStream[]{stream1, stream2};

        //Merge these documents and return an object of PdfDocumentBase
        PdfDocumentBase pdf = PdfDocument.mergeFiles(streams);

        //Save the result to a PDF file
        pdf.save("MergedPDF.pdf", FileFormat.PDF);

    }
}
相关推荐
树獭非懒1 天前
AI大模型小白手册|Embedding 与向量数据库
后端·python·llm
NE_STOP1 天前
MyBatis-配置文件解读及MyBatis为何不用编写Mapper接口的实现类
java
唐叔在学习1 天前
就算没有服务器,我照样能够同步数据
后端·python·程序员
曲幽1 天前
FastAPI流式输出实战与避坑指南:让AI像人一样“边想边说”
python·ai·fastapi·web·stream·chat·async·generator·ollama
Flittly1 天前
【从零手写 AI Agent:learn-claude-code 项目实战笔记】(1)The Agent Loop (智能体循环)
python·agent
后端AI实验室1 天前
用AI写代码,我差点把漏洞发上线:血泪总结的10个教训
java·ai
vivo互联网技术1 天前
ICLR2026 | 视频虚化新突破!Any-to-Bokeh 一键生成电影感连贯效果
人工智能·python·深度学习
程序员清风1 天前
小红书二面:Spring Boot的单例模式是如何实现的?
java·后端·面试
belhomme1 天前
(面试题)Redis实现 IP 维度滑动窗口限流实践
java·面试