pom 引入
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>3.0.2</version>
</dependency>
添加书签
public static void doBook(PDDocument document, String title, LinkedHashMap<Integer, String> pageIndexs) {
PDDocumentOutline documentOutline = new PDDocumentOutline();
document.getDocumentCatalog().setDocumentOutline(documentOutline);
documentOutline.openNode();
PDOutlineItem pagesOutline = new PDOutlineItem();
pagesOutline.openNode();
pagesOutline.setTitle(title);
documentOutline.addLast(pagesOutline);
for (Entry<Integer, String> e : pageIndexs.entrySet()) {
PDPageDestination pageDestination = new PDPageFitWidthDestination();
pageDestination.setPage(document.getPage(e.getKey()));
PDOutlineItem bookmark = new PDOutlineItem();
bookmark.setDestination(pageDestination);
bookmark.setTitle(e.getValue());
pagesOutline.addLast(bookmark);
}
PDPageDestination pageDestination = new PDPageFitWidthDestination();
pageDestination.setPage(document.getPage(document.getNumberOfPages() - 1));
PDOutlineItem bookmark = new PDOutlineItem();
bookmark.setDestination(pageDestination);
bookmark.setTitle("end尾页");
pagesOutline.addLast(bookmark);
}
合并pdf
private static void combine(List<CombineEntity> files, File dist) throws IOException {
try (PDDocument document = new PDDocument()) {
LinkedHashMap<Integer, String> books = new LinkedHashMap<Integer, String>();
int bookIndex = 0;
for (int index = 0; index < files.size(); index++) {
CombineEntity com = files.get(index);
PDDocument d = Loader.loadPDF(com.file);
int pageNumber = d.getNumberOfPages();
int start = 0;
int end = pageNumber;
if (com.start != com.end) {
start = com.start;
end = com.end;
}
for (int i = start; i < end; i++) {
document.importPage(d.getPage(i));
}
books.put(bookIndex, com.file.getName());
bookIndex += (end - start);
}
PDFUtils.doBook(document, "book marks", books);
document.save(dist);
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public static class CombineEntity {
private int start;
private int end;
private File file;
}