It turned out that the PDF uses bookmarks, not TOC.
The solution that works with bookmarks is shown here:
http://forum.pdfsharp.net/viewtopic.php?p=6660#p6660
An existing file is opened for modifications, a new page is inserted at the beginning 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); }
source share