PDFsharp & MigraDoc Foundation
https://forum.pdfsharp.net/

PDF Outlines are not preserved
https://forum.pdfsharp.net/viewtopic.php?f=2&t=2466
Page 1 of 1

Author:  benfosterdev [ Wed May 29, 2013 7:15 pm ]
Post subject:  PDF Outlines are not preserved

Below is the code we are using to "bundle" PDFs. For each document we add to the "source" bundle we want to add a Bookmark. The issue is that the root outline is not preserved the next time we open the bundle.

Code:
        public static void Concatenate(Stream source, Stream[] inputs)
        {
            PdfDocument sourceDoc = null;
            PdfOutline outline;

            try
            {
                sourceDoc = PdfReader.Open(source, PdfDocumentOpenMode.Modify);
            }
            catch // create the source doc (bundle) if it doesn't exist
            {
                sourceDoc = new PdfDocument();

                // create first page so we can add outline
                var rootPage = sourceDoc.Pages.Count > 0 ? sourceDoc.Pages[0] : sourceDoc.AddPage();
                XGraphics gfx = XGraphics.FromPdfPage(rootPage);
                gfx.DrawString("Bundle", new XFont("Verdana", 16), XBrushes.Black, 20, 50, XStringFormats.Default);
            }

            // for some reason not detecting outlines
            if (sourceDoc.Outlines.HasOutline)
            {
                outline = sourceDoc.Outlines[0];
            }
            else
            {
                outline = sourceDoc.Outlines.Add("Root", sourceDoc.Pages[0], true, PdfOutlineStyle.Bold);
            }

            foreach (var input in inputs)
            {
                var inputDoc = PdfReader.Open(input, PdfDocumentOpenMode.Import);

                bool addBookmark = true;

                foreach (PdfPage page in inputDoc.Pages)
                {
                    var newPage = sourceDoc.AddPage(page);

                    if (addBookmark)
                    {
                        // Add a bookmark for first page in this Document
                        outline.Outlines.Add("Document Added " + DateTime.UtcNow.ToString(), newPage, true);
                        addBookmark = false;
                    }
                }
            }

            sourceDoc.Save(source);
        }


Also is there a better way to check if the source document exists/is valid than wrapping in a try/catch?

Page 1 of 1 All times are UTC
Powered by phpBB® Forum Software © phpBB Group
https://www.phpbb.com/