How to add an additional page to existing pdf while keeping bookmarks? (PDFSharp etc.)
Asked Answered
B

1

7

I have got a PDF, and I would like to add an additional page to it, ideally as the first page. I have been able to achieve this with PDFSharp, but the problem is that the original PDF contains bookmarks, which I would like to maintain. Using PDFSharp seems to delete the bookmarks, or at least I am not aware of any options or commands to save the original TOC with the newly created PDF that contains the additional page.

Does anybody know how to keep the TOC with PDFSharp or maybe any other .NET libraries, ideally free ones, that would allow me to add a page to an existing PDF and to maintain its bookmarks? (I am aware that adding a page as the first page would invalidate the page refs, that's why adding a page as the last page is also ok.)

Thanks all!

Breazeale answered 21/1, 2013 at 13:54 Comment(0)
H
8

It turned out that the PDF file uses bookmarks, not a TOC.

A solution that works with bookmarks is shown here:
http://forum.pdfsharp.net/viewtopic.php?p=6660#p6660

The existing file is opened for modifications, a new page is inserted at the start of the document - and all bookmarks still work.

Here's the code snippet:

static void Main(string[] args)
{
    const string filename = "sample.pdf";
    File.Copy(Path.Combine("D:\\PDFsharp\\PDFfiles\\sample\\", filename),
      Path.Combine(Directory.GetCurrentDirectory(), filename), true);

    // Open an existing document for editing and loop through its pages
    PdfDocument document = PdfReader.Open(filename);
    var newPage = document.InsertPage(0);

    // Get an XGraphics object for drawing
    XGraphics gfx = XGraphics.FromPdfPage(newPage);

    // Create a font
    XFont font = new XFont("Times New Roman", 20, XFontStyle.BoldItalic);

    // Draw the text
    gfx.DrawString("Hello, World!", font, XBrushes.Black,
      new XRect(0, 0, newPage.Width, newPage.Height),
      XStringFormats.Center);

    document.Save(filename);
    // ...and start a viewer.
    Process.Start(filename);
}
Have answered 23/1, 2013 at 10:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.