Java - Merge Base64 PDF



我需要合并多个base64 pdf文件。我该怎么做呢?

OutputStream string = null;
File file1 = new File(
"/Users/guilherme.floriano/Desktop/teste1.pdf");
File file2 = new File(
"/Users/guilherme.floriano/Desktop/boleto.pdf");
// Instantiating PDFMergerUtility class
PDFMergerUtility obj = new PDFMergerUtility();
// Setting the destination file path
obj.setDestinationFileName(
"/Users/guilherme.floriano/Desktop/newMerged.pdf");

// Add all source files, to be merged
obj.addSource(file1);
obj.addSource(file2);
// Merging documents
obj.mergeDocuments(null);

System.out.print(string);
System.out.println(
"PDF Documents merged to a single file");

我想要这个,但是,没有文件,只有base64字符串。

假设您使用PDFBox,有一个版本的addSource()方法接受一个inputStream作为参数,因此您可以考虑将base64字符串转换为流:

String b64data = "....";
ByteArrayInputStream bais = new ByteArrayInputStream(b64data.getBytes());
obj.addSource(Base64.getDecoder().wrap(bais));

合并Base64字符串非常简单,您使用atob.js或Base64 -decode将它们转换为二进制文件对象,例如File1.bin File2.bin,然后使用适当的合并工具,因此对于PDF,您可以使用一个可以交错PDF对象的合并工具(因为PDF是多种风格的文件三明治,每个都有十进制文件地址)

PDF处理是资源密集型的,所以理想情况下,你需要为CPU处理器隔行保留内存,并将大数据(其仍有待解压缩和解码的十进制块)转储到文件存储中,因此将PDF作为文件(它们必须用于处理)通常更有效

mergepdf -Output merge .pdf File1.bin File2.bin

对于Java来说,最常用的合并工具是PDFbox

//Instantiating PDFMergerUtility class
PDFMergerUtility PDFmerger = new PDFMergerUtility();

//Setting the destination file
PDFmerger.setDestinationFileName("C:\Examples\merged.pdf");

//adding the source files
PDFmerger.addSource(file1);
PDFmerger.addSource(file2);

//Merging the two documents
PDFmerger.mergeDocuments();
System.out.println("Documents merged");

最新更新