原创:转载需注明原创地址 https://www.cnblogs.com/fanerwei222/p/12023314.html
开发过程中有用到PDF合成, 记录一下合成的方法和代码.
使用工具 : itextpdf
<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf --> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.13</version> </dependency>
合成工具类:
import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.pdf.PdfCopy; import com.itextpdf.text.pdf.PdfImportedPage; import com.itextpdf.text.pdf.PdfReader; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.springframework.util.Assert; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.List; /** * TODO * 合并PDF流工具类 */ public class MergePdfUtils { /** * 根据字节数组合并PDF * @param pdfBytes pdf字节流数组 * @param len 字节流数组总长度 * @throws IOException * @throws DocumentException */ public static byte[] mergePdfBytes(List<byte[]> pdfBytes, int len) throws IOException, DocumentException { Assert.notEmpty(pdfBytes, "参数不能为空!"); byte[] newPdfByte = new byte[len]; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { Document document = new Document(new PdfReader(pdfBytes.get(0)).getPageSize(1)); PdfCopy copy = new PdfCopy(document, outputStream); document.open(); PdfReader reader = null; for (int i = 0; i < pdfBytes.size(); i++) { reader = new PdfReader(pdfBytes.get(i)); int n = reader.getNumberOfPages(); for (int j = 1; j <= n; j++) { document.newPage(); PdfImportedPage page = copy.getImportedPage(reader, j); copy.addPage(page); } } document.close(); newPdfByte = outputStream.toByteArray(); } catch (IOException | DocumentException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(outputStream); } return newPdfByte; } }
还有一个合成为文件的工具类:
import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.pdf.PdfCopy; import com.itextpdf.text.pdf.PdfImportedPage; import com.itextpdf.text.pdf.PdfReader; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; /** * TODO * 合并PDF为文件 */ public class MergePdfFile { /** * 合成为文件 * @param files 文件所在的路径列表 * @param newfile 新文件的路径 * @throws IOException * @throws DocumentException */ public static void mergePdfFiles(List<String> files, String newfile) throws IOException, DocumentException { Document document = new Document(new PdfReader(files.get(0)).getPageSize(1)); PdfCopy copy = new PdfCopy(document, new FileOutputStream(newfile)); document.open(); for (int i = 0; i < files.size(); i++) { PdfReader reader = new PdfReader(files.get(i)); int n = reader.getNumberOfPages(); for (int j = 1; j <= n; j++) { document.newPage(); PdfImportedPage page = copy.getImportedPage(reader, j); copy.addPage(page); } } document.close(); } }