We have created our PDF using Aspose PDF library version 23.5 and generated the Table of Contents (TOC). The generated TOC has been placed at the end of the PDF document.
Now, how can we move the TOC to the top of the document and update the page numbers correctly in the TOC?
@kchowdhury
To move the Table of Contents (TOC) from the end of your PDF document to the first page and update the page numbers correctly, you can follow these steps using the Aspose.PDF library:
-
Insert a New Page for the TOC: You will need to insert a new page at the beginning of your document where the TOC will be placed.
-
Create the TOC: You can create a TocInfo
object to hold the TOC information, including the title and the entries.
-
Add TOC Entries: For each section of your document, create a heading that links to the corresponding page. You will need to specify the destination page for each heading.
-
Update Page Numbers: Ensure that the page numbers in the TOC reflect the correct pages after moving it to the front.
Here is a sample code snippet in C# that demonstrates how to achieve this:
using Aspose.Pdf;
using Aspose.Pdf.Text;
public class MoveTOC
{
public static void Run()
{
// Load an existing PDF file
Document doc = new Document("path/to/your/document.pdf");
// Insert a new page at the beginning for the TOC
Page tocPage = doc.Pages.Insert(1);
// Create TOC information
TocInfo tocInfo = new TocInfo();
TextFragment title = new TextFragment("Table Of Contents");
title.TextState.FontSize = 20;
title.TextState.FontStyle = FontStyles.Bold;
// Set the title for TOC
tocInfo.Title = title;
tocPage.TocInfo = tocInfo;
// Add TOC entries
for (int i = 1; i < doc.Pages.Count; i++)
{
Heading heading = new Heading(1);
TextSegment segment = new TextSegment();
heading.TocPage = tocPage;
heading.Segments.Add(segment);
heading.DestinationPage = doc.Pages[i];
segment.Text = "Page " + i.ToString(); // Update this to your section titles
tocPage.Paragraphs.Add(heading);
}
// Save the updated document
doc.Save("path/to/your/updated_document.pdf");
}
}
In this code:
- A new page is inserted at the beginning of the document.
- The TOC title is set, and entries are created for each page in the document.
- The TOC is saved in the updated PDF file.
Make sure to adjust the titles and the number of pages according to your document’s structure. This will effectively move your TOC to the first page and ensure that the page numbers are updated correctly.
For more detailed examples and additional functionalities, you can refer to the Aspose documentation on working with TOC here and check the provided code examples on GitHub for further insights.
Sources:
[1]: Overview|Aspose.PDF for .NET - Aspose Documentation