最近遇到一个需求,需要将多个pdf合并为同一个pdf
直接上代码
import com.lowagie.text.Document;
import com.lowagie.text.pdf.PdfCopy;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;
import lombok.extern.slf4j.Slf4j;
import java.nio.file.Files;
import java.nio.file.Paths;
@Slf4j
public class PdfUtil {
public static boolean mergePdfFiles(String[] files, String newfile) {
boolean retValue = false;
Document document = null;
PdfCopy copy = null;
PdfReader reader = null;
try {
document = new Document(new PdfReader(files[0]).getPageSize(1));
copy = new PdfCopy(document, Files.newOutputStream(Paths.get(newfile)));
document.open();
for (String file : files) {
reader = new PdfReader(file);
int n = reader.getNumberOfPages();
for (int j = 1; j <= n; j++) {
document.newPage();
PdfImportedPage page = copy.getImportedPage(reader, j);
copy.addPage(page);
}
reader.close();
}
retValue = true;
} catch (Exception e) {
log.error("合并pdf失败"+e.getMessage());
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
if (copy != null) {
copy.close();
}
if (document != null) {
document.close();
}
}
return retValue;
}
}