Can I merge elements from two PDF to a final PDF with PDFBox (or other library)?
I'm not looking for page concatenation but merging page elements:
Can I merge elements from two PDF to a final PDF with PDFBox (or other library)?
I'm not looking for page concatenation but merging page elements:
The task of the OP is to merge two pages into one, keeping each object at its present location on the page.
For doing this PDFBox provides the Overlay
class. Given two PDDocument
instances document1
and document2
, you can simply do
Overlay overlay = new Overlay();
overlay.setOverlayPosition(Overlay.Position.FOREGROUND);
overlay.setInputPDF(document1);
overlay.setAllPagesOverlayPDF(document2);
Map<Integer, String> ovmap = new HashMap<Integer, String>();
overlay.overlay(ovmap);
document1.save("");
overlay.close();
to overlay the second over the first document.
But the Overlay
can be used for more complex overlaying tasks. In particular it allows you to also set specific PDFs to overlay only odd, only even pages, or only explicitly specified pages with.
As an example have a look at the source of the PDFBox tool OverlayPDF
.
A word of warning, though: Only the page content of the extra documents is used for overlaying, all kinds of annotations are ignored. Also don't expect tags to be copied.