杭州网站建设维护,广州建工集团有限公司官网,怎么不花钱做网站,河北省建设项目信息网站一.前言
我们将从以下两个方面向您展示如何将多个PDF文件合并为一个PDF#xff1a; 1. 将文件中的多个 PDF 合并为单个 PDF 2. 将流中的多个 PDF 合并为单个 PDF
1. 了解 Spire.PDF 库
要在 Java 中合并 PDF 文件#xff0c;我们将使用Spire.PDF 库。Spire.PDF for Java 是…一.前言
我们将从以下两个方面向您展示如何将多个PDF文件合并为一个PDF 1. 将文件中的多个 PDF 合并为单个 PDF 2. 将流中的多个 PDF 合并为单个 PDF
1. 了解 Spire.PDF 库
要在 Java 中合并 PDF 文件我们将使用Spire.PDF 库。Spire.PDF for Java 是一个 PDF API使 Java 应用程序能够在不使用 Adobe Acrobat 的情况下读取、写入和保存 PDF 文档。它提供了用于操作 PDF 文件的广泛功能包括将多个 PDF 文件合并到单个文档中。
在我们使用 Spire.PDF 合并 PDF 文件之前我们需要将其依赖项添加到我们的 Java 项目中。我们可以通过向 Maven 项目添加以下依赖项来实现此目的
repositoriesrepositoryidcom.e-iceblue/idnamee-iceblue/nameurlhttps://repo.e-iceblue.com/nexus/content/groups/public//url/repository
/repositoriesdependenciesdependencygroupIde-iceblue/groupIdartifactIdspire.pdf/artifactIdversion9.5.6/version/dependency
/dependencies
2.将文件中的多个 PDF 合并为单个 PDF
获取要合并的文档的路径并将其存储在 String 数组中。使用PdfDocument.mergeFiles()方法合并选定的 PDF 文件。使用PdfDocumentBase.save()方法保存 PDF 文档。
import com.spire.pdf.*;public class mergePDF {public static void main(String[] args) throws Exception {//Get the paths of the documents to be mergedString[] files new String[] {D:\\sample.pdf,D:\\sample1.pdf};//Merge documents and return an object of PdfDocumentBasePdfDocumentBase pdf PdfDocument.mergeFiles(files);//Save the result to a PDF filepdf.save(MergedPDF.pdf, FileFormat.PDF);}
}
3.将流中的多个 PDF 合并为单个 PDF
从流中加载 PDF 并将其合并为新的 PDF 是处理多个 PDF 文档而无需将它们保存到磁盘的便捷有效的方法。当处理您不想存储在本地驱动器上的大型或敏感文件时此方法特别有用。Spire.PDF还支持从流中加载PDF然后将它们组合成一个新的PDF文件。
获取 PDF 流的路径然后将它们存储到FileInputStream数组中。使用PdfDocument.mergeFiles()方法合并选定的 PDF 文件。使用PdfDocumentBase.save()方法保存 PDF 文档。
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 PdfDocumentBasePdfDocumentBase pdf PdfDocument.mergeFiles(streams);//Save the result to a PDF filepdf.save(MergedPDF.pdf, FileFormat.PDF);}
}