需求说明:
第一种方式需要将多个PDF文件或者文件流合并为一个文件
使用e-iceblue 官网地址。注意:这是收费软件,合并的文件会有水印。
在pom.xml文件中引入Jar包
com.e-iceblue e-iceblue https://repo.e-iceblue.com/nexus/content/groups/public/ e-iceblue spire.pdf 5.4.0
private static void mergePDF() throws FileNotFoundException {
File file1 = new File("/Users/tianming/Downloads/附件.pdf");
File file2 = new File("/Users/tianming/Downloads/附件.pdf");
String outputFile = "/Users/tianming/Downloads/合并附件.pdf";
FileInputStream stream1 = new FileInputStream(file1);
FileInputStream stream2 = new FileInputStream(file2);
//加载PDF示例文档
InputStream[] streams = new FileInputStream[]{stream1, stream2};
//合并PDF文档
PdfDocumentBase doc = PdfDocument.mergeFiles(streams);
//保存文档
doc.save(outputFile);
doc.close();
}
第二种方式
使用pdfbox依赖 apache官网
org.apache.pdfbox pdfbox 2.0.22
private static void mergePDFbox(List第三种方式list, String outputFile){ // 合并PDF文档法二 File outFile = new File(outputFile); PDFMergerUtility merger = new PDFMergerUtility(); list.forEach(merger::addSource); merger.setDestinationFileName(outFile.getName()); try { // 合并PDF merger.mergeDocuments(null); } catch (IOException e) { log.error("Pdf Merge error: ", e); } }
使用itext 官方地址
com.itextpdf itextpdf 5.5.13.3
private static byte[] mergePdfFiles(ListinputStreams, String outFile) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); Document document = new Document();// 创建一个新的PDF byte[] pdfs = new byte[0]; try { PdfCopy copy = new PdfCopy(document, bos); document.open(); for (InputStream is : inputStreams) {// 取出单个PDF的数据 PdfReader reader = new PdfReader(stream2Byte(is)); int pageTotal = reader.getNumberOfPages(); for (int pageNo = 1; pageNo <= pageTotal; pageNo++) { document.newPage(); PdfImportedPage page = copy.getImportedPage(reader, pageNo); copy.addPage(page); } reader.close(); } document.close(); pdfs = bos.toByteArray(); bos.close(); copy.close(); FileCopyUtils.copy(pdfs, new File(outFile)); } catch (DocumentException | IOException e) { log.error("合并PDF出错:" + e); } return pdfs; } private static byte[] stream2Byte(InputStream inputStream) { byte[] buffer = new byte[0]; try (InputStream fis = inputStream; ByteArrayOutputStream bos = new ByteArrayOutputStream()) { byte[] b = new byte[1024]; int n; while ((n = fis.read(b)) != -1) { bos.write(b, 0, n); } buffer = bos.toByteArray(); } catch (IOException e) { } return buffer; }



