Add TOC to existing PDF document in C# using Aspose.PDF for .NET

I have a PDF document that already contains headings. I would like to add a table of contents with page numbers to the first page of this PDF that references all the existing headings in the existing PDF document. I have attached my sample PDF document.

Hi Steve,

Thanks for your inquiry.

Unfortunately for now Aspose.Pdf does not support to read headings from PDF document so that they can be added into TOC with their page numbers. For that purpose we already have logged an enhancement request as PDFNET-35058 in our issue tracking system. I have associated your inquiry with earlier logged request as well. As soon as we have some significant progress on that we will definitely let you know.

However for now you may add TOC into existing PDF which will have reference of each page inside document. Please check the following code snippet to achieve this feature and for more information you may check “Working with TOC” article in documentation.

Document doc = new Document(dataDir + “SamplewithNOTOC.pdf”);
Aspose.Pdf.Page tocPage = doc.Pages.Insert(1);

TocInfo tocInfo = new TocInfo();

TextFragment title = new TextFragment("Table Of Contents");

title.TextState.FontSize = 20;

title.TextState.FontStyle = FontStyles.Bold;

tocInfo.Title = title;

tocPage.TocInfo = tocInfo;

string[] titles = new string[doc.Pages.Count - 1];

for (int i = 0; i < doc.Pages.Count - 1; i++)

{

    int pageLinkTitle = i + 1;

    titles[i] = "Page " + pageLinkTitle.ToString();

    Aspose.Pdf.Heading heading2 = new Aspose.Pdf.Heading(1);

    TextSegment segment2 = new TextSegment();

    heading2.TocPage = tocPage;

    heading2.Segments.Add(segment2);

    heading2.DestinationPage = doc.Pages[i + 2];

    heading2.Top = doc.Pages[i + 2].Rect.Height;

    segment2.Text = titles[i];

    tocPage.Paragraphs.Add(heading2);

}

doc.Save(dataDir + "TOC_Output.pdf");

I have also attached the output file for your reference. For the enhancement request, please be patient and spare us a little time. We will keep you updated on the status within this thread. We are sorry for this inconvenience.

Best Regards,