版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/Eiceblue/article/details/83861135
这篇文章主要介绍如何在Java应用程序中来实现合并PDF文档的功能。
使用组件:
Spire.PDF for Java
使用以下代码前,需要下载Spire.PDF for Java包并解压缩,然后lib文件夹下,导入Spire.Pdf.jar包到你的Java应用程序中。
import com.spire.pdf.*;
public class MergePDFs {
public static void main(String[] args)
{
//合并PDF文件
PdfDocumentBase doc = PdfDocument.mergeFiles(new String[]{"File1.pdf","File2.pdf","File3.pdf"});
//保存结果文件
doc.save("Merge.pdf", FileFormat.PDF);
}
}
此外Spire.PDF for Java还支持通过Stream来合并PDF文件:
import com.spire.pdf.*;
import java.io.*;
public class MergePDFs {
public static void main(String[] args) throws Exception
{
FileInputStream stream1 = new FileInputStream(new File("File1.pdf"));
FileInputStream stream2 = new FileInputStream(new File("File2.pdf"));
FileInputStream stream3 = new FileInputStream(new File("File3.pdf"));
InputStream[] streams = new FileInputStream[]{stream1, stream2, stream3};
//通过Stream合并文件
PdfDocumentBase doc = PdfDocument.mergeFiles(streams);
//保存结果文件
doc.save("Merge.pdf", FileFormat.PDF);
doc.close();
}
}
合并前:
合并后: