Page number only appears on first page of PDF file

Hi. I’m trying to add page numbers to a PDF document but only see it on the first page, and it says “Page 1 of 1”. Here’s the relevant code (based on code from this documentation):

byte[] pdfBytes = null;

using (var ms = new MemoryStream())
{
	var pdfDocument = new Document();
	var htmlFragment = new HtmlFragment(htmlString);
	pdfDocument.Pages.Add().Paragraphs.Add(htmlFragment);
	PageNumberStamp pageNumberStamp = new PageNumberStamp();
	pageNumberStamp.Background = false;
	pageNumberStamp.Format = "Page # of " + pdfDocument.Pages.Count;
	pageNumberStamp.BottomMargin = 15;
	pageNumberStamp.HorizontalAlignment = HorizontalAlignment.Center;
	pageNumberStamp.StartingNumber = 1;
	pageNumberStamp.TextState.Font = FontRepository.FindFont("Arial");
	pageNumberStamp.TextState.FontSize = 12.0F;

	for (int i = 1; i <= pdfDocument.Pages.Count; i++)
	{
		pdfDocument.Pages[i].AddStamp(pageNumberStamp);
	}

	pdfDocument.Save(ms);
	pdfDocument.Dispose();
	
	pdfBytes = ms.ToArray();
}

What am I doing wrong? Thank you.

Found the issue: it needs this right after the .Add(htmlFragment). This calculates the page numbers so we can move to adding the stamp:

pdfDocument.ProcessParagraphs();

@asposeFriend9

It is nice to know that you were able to resolve the issue. Yes, ProcessParagraphs() method updates the document state and page count gets refreshed for the automatically added pages. In case you need any kind of assistance, please feel free to create a new topic.

1 Like