I found that if I insert a TextFragment
that contains text for more than 1 page, and add page number stamp to each page, the page number is only added to the first page and the Document.Page.Count
isn’t calculated correctly:
var pdfDocument = new Document();
var tocPage = pdfDocument.Pages.Add();
tocPage.TocInfo = new TocInfo{Title = new TextFragment("Table of Content")};
var firstPage = pdfDocument.Pages.Add();
// Generate a 200 line text.
var longText = string.Concat(Enumerable.Range(0, 200).Select(i => i + Environment.NewLine));
firstPage.Paragraphs.Add(new TextFragment(longText));
pdfDocument.ProcessParagraphs();
tocPage.Paragraphs.Add(new Heading(1)
{
TocPage = tocPage,
DestinationPage = firstPage,
Segments = {new TextSegment {Text = "Main content section"}}
});
firstPage.AddStamp(new PageNumberStamp());
var secondPage = pdfDocument.Pages.Add();
secondPage.Paragraphs.Add(new TextFragment("Total page count: " + pdfDocument.Pages.Count));
tocPage.Paragraphs.Add(new Heading(1)
{
TocPage = tocPage,
DestinationPage = secondPage,
Segments = {new TextSegment {Text = "Total page count section"}}
});
secondPage.AddStamp(new PageNumberStamp());
After some research, I found an Aspose blog post back in 2015 saying that calling Document.ProcessParagraphs
function can force the generation of the pages, so I updated my code to call this function:
var pdfDocument = new Document();
var tocPage = pdfDocument.Pages.Add();
tocPage.TocInfo = new TocInfo{Title = new TextFragment("Table of Content")};
var firstPage = pdfDocument.Pages.Add();
// Generate a 200 line text.
var longText = string.Concat(Enumerable.Range(0, 200).Select(i => i + Environment.NewLine));
firstPage.Paragraphs.Add(new TextFragment(longText));
// Call this to force page generation.
pdfDocument.ProcessParagraphs();
tocPage.Paragraphs.Add(new Heading(1)
{
TocPage = tocPage,
DestinationPage = firstPage,
Segments = {new TextSegment {Text = "Main content section"}}
});
var secondPage = pdfDocument.Pages.Add();
secondPage.Paragraphs.Add(new TextFragment("Total page count: " + pdfDocument.Pages.Count));
tocPage.Paragraphs.Add(new Heading(1)
{
TocPage = tocPage,
DestinationPage = secondPage,
Segments = {new TextSegment {Text = "Total page count section"}}
});
foreach (var page in pdfDocument.Pages)
{
page.AddStamp(new PageNumberStamp());
}
This fixes the incorrect page count but it duplicates the title of the table of content page (TocInfo.Title
).
After some testing, I found that each time the Document.ProcessParagraphs
function is called, it duplicates the title of the table of content page once more.
I’d like to know how I can generate a table of content page without duplicating the title, while keeping the page number and page count correct in this case.