-1

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:

enter image description here

Tobia
  • 9,165
  • 28
  • 114
  • 219
  • Please comment the close vote – Tobia Feb 07 '19 at 15:11
  • Both close votes are claiming your question is off-topic because it asks for a off-site resource recommendation. I assume the voters took your *"PDFBox (or other library)"* as a request for a library recommendation. – mkl Feb 07 '19 at 17:25
  • *"merge elements from two PDF to a final PDF"* - What exactly do you mean by that? From your words I would have thought you mean something akin to what the `PdfVeryDenseMergeTool` for iText does, cf. [this answer](https://stackoverflow.com/a/29078954/1729265). Your image, on the other hand, looks more like something the PDFBox `Overlay` class and `OverlayPDF` tool do. – mkl Feb 07 '19 at 17:36
  • https://stackoverflow.com/questions/26256546/ – Tilman Hausherr Feb 07 '19 at 20:53
  • @mkl overlay is the answer. I follow this: https://snipplr.com/view/327056/pdfbox-overlaying-one-pdf-on-another/ – Tobia Feb 08 '19 at 12:26
  • @Tobia Do you want to make this an actual answer here or shall I? – mkl Feb 08 '19 at 13:44
  • Please proceed with the answer – Tobia Feb 08 '19 at 14:37

1 Answers1

0

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.

mkl
  • 90,588
  • 15
  • 125
  • 265