使用依赖 itextpdf,在maven repo里复制
我们要合并多个pdf,要使用到这个依赖库里面的com.itextpdf.kernel.utils包下的PdfMerger方法,具体参数根据实际需要
我这写了个domo test,可以用作参考
@Test
void mergePdf() {
final String filename = UUID.randomUUID().toString() + ".pdf";
try (final FileOutputStream out = new FileOutputStream(new File("/Users/alexzhang/Downloads/" + filename))) {
ConverterProperties properties = new ConverterProperties();
properties.setMediaDeviceDescription(new MediaDeviceDescription(MediaType.PRINT));
PdfWriter writer = new PdfWriter(out);
PdfDocument pdf = new PdfDocument(writer);
PdfMerger merger = new PdfMerger(pdf);
for (String waybillUrl : List.of("/Users/alexzhang/Downloads/1.pdf", "/Users/alexzhang/Downloads/2.pdf", "/Users/alexzhang/Downloads/3.pdf")) {
if (StringUtils.isEmpty(waybillUrl)) {
continue;
}
PdfDocument temp = new PdfDocument(new PdfReader(new ByteArrayInputStream(FileUtils.readFileToByteArray(new File(waybillUrl)))));
merger.merge(temp, 1, temp.getNumberOfPages());
temp.close();
}
pdf.close();
} catch (Exception ex) {
if (ex instanceof ConstraintViolationProblem) {
throw (ConstraintViolationProblem) ex;
}
throw new RuntimeException(ex);
}
}
需要注意的是这里的pdf.close(),或者使用merger.close()是一定要用的,不然可能合并后的pdf大小为0,而且打不开