PdfPig
PdfPig copied to clipboard
How to change the bookmarks/outlines destination when merge pdf files
when pdf files merged, the bookmarks/outlines destination's page number tend to update
In PdfBox 3, I can change pdPageDestination's retrievePageNumber code like this
@Test
void pdfMerge() {
val mergeUtil = new PDFMergerUtility();
try(val headerStream = new FileInputStream("/var/header.pdf");
val bodyStream = new FileInputStream("/var/body.pdf");
val footerStream = new FileInputStream("/var/footer.pdf");
val mergeStream = new ByteArrayOutputStream()) {
mergeUtil.addSource(headerStream);
mergeUtil.addSource(bodyStream);
mergeUtil.addSource(footerStream);
mergeUtil.setDestinationStream(mergeStream);
mergeUtil.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
val document = Loader.loadPDF(mergeStream.toByteArray());
document.getDocumentCatalog().getDocumentOutline().children().forEach(x -> {
try {
val pdPageDestination = document.getDocumentCatalog().findNamedDestinationPage((PDNamedDestination) x.getDestination());
pdPageDestination.setPageNumber(pdPageDestination.retrievePageNumber() + 1);
x.children().forEach(y -> {
PDPageDestination pdPageDestination1 = null;
try {
pdPageDestination1 = document.getDocumentCatalog().findNamedDestinationPage((PDNamedDestination) y.getDestination());
pdPageDestination1.setPageNumber(pdPageDestination1.retrievePageNumber() + 1); // update page number
} catch (IOException e) {
e.printStackTrace();
}
});
} catch (IOException e) {
e.printStackTrace();
}
});
document.save("/var/" + UUIDUtils.generate() + ".pdf");
} catch (Exception ex) {
ex.printStackTrace();
}
}
but in PdfPig the BookmarkNode is readonly