Free Support Forum - aspose.com

Create TOC and Add Page Numbers in PDF document using Aspose.PDF for .NET

AsposePdfBug.zip (3.9 KB)
test.pdf (71.2 KB)
Hello,
There are two problems I am experiencing with the attached project:

  1. I create a pdf, set page numbers and TOC. The result is that no page numbers are set in the final document.
  2. TOC header is repeated twice.

Please see the attached project and resulting pdf. You will have to add Aspose.PDF.dll to the project. I removed it because the project was too larget. Thank you.

@mpogorelov

We have tested the scenario in our environment using your code snippet with some modifications and were unable to notice any issue. Please check following code snippet which we used to add TOC and Page Numbers at the footer of PDF Page:

Document doc = new Document();
var CurrentPage = doc.Pages.Add();
Heading title = new Heading(1);
title.Text = "Submittal";
title.HorizontalAlignment = HorizontalAlignment.Center;
title.TextState.FontSize = 30;
CurrentPage.Paragraphs.Add(title);
Page tocPage = doc.Pages.Insert(2);
TocInfo tocInfo = new TocInfo();
TextFragment title2 = new TextFragment("Table Of Contents");
title2.TextState.FontSize = 20;
title2.Margin.Bottom = 20;
tocInfo.Title = title2;
tocPage.TocInfo = tocInfo;
// save the Pdf
doc.Save(dataDir + "TOC.pdf");
using (var fs = new FileStream(dataDir + "TOC.pdf", FileMode.Open, FileAccess.ReadWrite))
{
  doc = new Document(fs);
  for (int i = 2; i <= doc.Pages.Count; ++i)
  {
    var pg = doc.Pages[i];
    AddPageNumber(pg, i - 1);
   }
   doc.Save();
   doc.Dispose();
}

private static void AddPageNumber(Page pg, int PageNumber)
{
 TextStamp footerText = new TextStamp(PageNumber.ToString());
  footerText.HorizontalAlignment = HorizontalAlignment.Center;
  footerText.VerticalAlignment = VerticalAlignment.Bottom;
  pg.AddStamp(footerText);
}

Well, I need the original code to work. Such as:
doc.Save(targetPath, new PdfSaveOptions() { CloseResponse = true });
doc.Dispose();
the reason being when you create a very large files, just doc.Save() still keeps the handle to the file open and prevents it from being opened.

@mpogorelov

You can surely save the document as per your requirements. We have tested the scenario in a console application which was why shared the snippet that way. You can please modify it for saving the document as per your needs. In case you face any issue, please feel free to let us know.

thank you, that worked

1 Like

@mpogorelov

It is good to know that suggested code snippet worked for you. Please keep using our API and in case you need further assistance, please feel free to create a new topic.