Search code examples
c#pdfsharpmigradoc

How to Define a PDF Outline Using MigraDoc


I noticed when using MigraDoc that if I add a paragraph with any of the heading styles (e.g., "Heading1"), an entry is automatically placed in the document outline. My question is, how can I add entries in the document outline without showing the text in the document? Here is an example of my code:

var document = new Document();
var section = document.AddSection();
// The following line adds an entry to the document outline, but it also
//     adds a line of text to the current section.  How can I add an
//     entry to the document outline without adding any text to the page?
var paragraph = section.AddParagraph("TOC Level 1", "Heading1");

Solution

  • I realized after reading ThomasH's answer that I am already mixing PDFSharp and MigraDoc code. Since I am utilizing a PdfDocumentRenderer, I was able to add a custom outline to the PdfDocument property of that renderer. Here is an example of what I ended up doing to create a custom outline:

    var document = new Document();
    // Populate the MigraDoc document here
    ...
    
    // Render the document
    var renderer = new PdfDocumentRenderer(false, PdfFontEmbedding.Always)
    {
        Document = document
    };
    renderer.RenderDocument();
    
    // Create the custom outline
    var pdfSharpDoc = renderer.PdfDocument;
    var rootEntry = pdfSharpDoc.Outlines.Add(
        "Level 1 Header", pdfSharpDoc.Pages[0]);
    rootEntry.Outlines.Add("Level 2 Header", pdfSharpDoc.Pages[1]);
    
    // Etc.
    
    // Save the document
    pdfSharpDoc.Save(outputStream);