We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Add TOC to existing PDF

Hello,

I want to add TOC to existing PDF. In that I want to use TextFragmentAbsorber and want to get page numbers of that Textfragments and set them as destination page while adding TOC externally.

Could you please provide me sample code for the same.

Hi Ranjeeta,


Thanks for your inquiry.

Please check the following code snippet to achieve the functionality where I have determined the page of TextFragments and set them as destination page in TOC.

Document doc = new Document(dataDir + “SamplewithNOTOC.pdf”);<o:p></o:p>

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;

TextFragmentAbsorber tfa = new TextFragmentAbsorber("{your search term}");

doc.Pages.Accept(tfa);

foreach(TextFragment tf in tfa.TextFragments)

{

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

TextSegment segment2 = new TextSegment();

heading2.TocPage = tocPage;

heading2.Segments.Add(segment2);

heading2.DestinationPage = tf.Page;

heading2.Top = tf.Page.Rect.Height;

segment2.Text = tf.Text;

tocPage.Paragraphs.Add(heading2);

}

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


Please try above code to set the TextFragment's page as destination page in TOC and in case you still face any issue, please feel free to let us know.


Best Regards,