1

I want to replace a page from the targetDoc with a page from the srcDoc, however, I cannot find a way to preserve (or recreate) the bookmark (and the bookmark's position in the document's outline). The original page was pointed to by a bookmark in the document outline and I want this bookmark to stay right at its place pointing to a page which was inserted instead of original page. For example:

PdfDocument srcDoc=new PdfDocument(new PdfReader("c:\\temp\\srcdoc.pdf"));
PdfDocument targetDoc = new PdfDocument(new PdfReader("c:\\temp\\Untitled 1.pdf"),new PdfWriter("c:\\temp\\result.pdf"));

targetDoc.removePage(1);
  /* 
   * The bookmark to page is also removed with the removePage command.
   * How to preserve/recreate it to point to the page inserted in the following step?
   */

srcDoc.initializeOutlines(); // it doesn't affect the result
srcDoc.copyPagesTo(1, 1, targetDoc,1);

targetDoc.close();
srcDoc.close();
mkl
  • 90,588
  • 15
  • 125
  • 265
tomazz
  • 145
  • 6
  • I'm missing `srcDoc.initializeOutlines()` in your code. – Bruno Lowagie Jul 31 '18 at 15:13
  • But the srcDoc is without the outline - only the "c:\temp\Untitled 1.pdf" has bookmarks which I am trying to preserve when removing page from it and inserting a page in the same place. – tomazz Jul 31 '18 at 15:47
  • Then why not use `PdfMerger` instead? Now you're just copying a page from one document to another losing the context of the document you're copying the page from. – Bruno Lowagie Jul 31 '18 at 15:48
  • Well, I actually want to lose the context of the srcDoc and preserve the context of the targetDoc. In general the scenario is such that my "Untitled 1.pdf" (= targetDoc) has 100+ pages with multilayered images and some of these 100+ images/pages I need to have converted the format/flattened and leave the other pages intact. As I am not exactly a Java programmer I do this with Ghostscript, exporting the pages I need to redact from the targetDoc to the srcDoc and, lastly, I replace the original unflattened pages in the targetDoc with those converted and flattened in the srcDoc. – tomazz Jul 31 '18 at 17:17

1 Answers1

0

So, I just ended up storing the outline before modifying the target document (this answer was helpful when storing the outline: Get the page number from document outline (bookmarks)) and restoring it after the modification.

tomazz
  • 145
  • 6