关于java:Java-合并-PDF-文件

5次阅读

共计 1776 个字符,预计需要花费 5 分钟才能阅读完成。

PDF 文件具备可能在各种操作系统放弃文档外观以及反对丰盛的文档元素等特点,被宽泛用于电子书、产品描述、公司文告、网络资料、邮件等。一个 PDF 文件通常蕴含多个页面,文字、图像、超链接、动图或其余元素就出现在这些页面上。有时须要将多个 PDF 文件的页面合并到一个 PDF 文件中,把扩散的文档内容进行交融,这样的文档合并能够通过简略的编程实现。
要达到此目标,须要用到收费库 Free Spire.PDF for Java, 可通过以下形式装置。

1. 应用 Maven

复制以下代码到我的项目文件夹下的“pom.xml“文件中,即可引入 JAR 文件。

<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.free</artifactId>
        <version>5.1.0</version>
    </dependency>
</dependencies>

2. 手动增加 JAR 文件

在 Spire.Doc for Java 免费版官网下载免费版,解压后,在“Project Structure“中,找到”Modules“,而后在其中的“Dependencies”中,增加解压出的“lib”文件夹下的 Spire.Doc.jar 文件。

合并 PDF 文件

操作步骤:

  • Create a collection of PDF documents’locations.
  • Create a collection of PdfDocument class.
  • Create an object of PdfDocument class.
  • Loop through the PDF documents’collection to load each file using Document.loadFromFile() method.
  • Append the PDF documents using PdfDocuments[].appendPage() method.
  • Loop through the PDF documents to get the pages and insert them to the first PDF file using PdfDocument.insertPage() method.
  • Save the PDF document.

代码示例

Java

import com.spire.pdf.*;

public class MergePDFDocuments {public static void main(String[] args) {
        //Create a list of the PDF Documents
        String[] files = new String[]
                {
                        "D:/Samples/Sample1.pdf",
                        "D:/Samples/Sample2.pdf",
                        "D:/Samples/Sample3.pdf"
                };
        //Open pdf documents
        PdfDocument[] docs = new PdfDocument[files.length];
        PdfDocument doc = new PdfDocument();
        for (int i = 0; i < files.length; i++) {docs[i] = new PdfDocument();
            docs[i].loadFromFile(files[i]);
        }
        //Append document
        docs[0].appendPage(docs[1]);

        //Import pages
        for (int i = 0; i < docs[2].getPages().getCount(); i = i + 2) {docs[0].insertPage(docs[2], i);
        }

        // Save pdf file
        String output = "output/mergeDocuments.pdf";
        docs[0].saveToFile(output, FileFormat.PDF);
    }
}

以上援用的是收费的 Free Spire.PDF for Java 中的 JAR 文件。

正文完
 0