TheDiamondDoge
TheDiamondDoge

Reputation: 5

PDFBox: how to properly copy annotation from one pdf to another

I am trying to copy annotations from one pdf to another. But copying even 1 annotation DOUBLES the size of outputing pdf file.

Please find below simple code sample:

    PDDocument pdf = PDDocument.load(new File("test1.pdf"));
    PDDocument pdf2 = PDDocument.load(new File("test/test1.pdf"));
    List<PDAnnotation> pdfAnnotations1 = pdf.getPage(0).getAnnotations();
    List<PDAnnotation> pdfAnnotations2 = pdf2.getPage(0).getAnnotations();

    pdfAnnotations1.add(pdfAnnotations2.get(0));
    pdf.save("test1.pdf");

If I try to open this output file with Adobe Reader and save it again - size comes back to normal. Any thoughts? Thank you very much in advance for any help.

Upvotes: 0

Views: 962

Answers (1)

Tilman Hausherr
Tilman Hausherr

Reputation: 18946

Each annotation points back to the page where it is. So you need to correct that as well by calling pdfAnnotations1.get(0).setPage(pdf.getPage(0)).

The size increase is because without the call I described, the annotation will point back to the old page, which points back to its parent, etc.

Upvotes: 1

Related Questions