i get error Document was closed when try to display page number on pdf ?

Ahmed Salah Abed Elaziz 390 Reputation points
2024-03-26T10:12:55.9566667+00:00

I try to display page number at the the bottom of every page when export to pdf

but i get error as below

I get error

iText.Kernel.Exceptions.PdfException: 'Document was closed. It is impossible to execute action.'

on line

int pageCount = pdfDocument.GetNumberOfPages();

so how to solve this error by modification code on answer

using (MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(pdfHtml)))
 {
     ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
     PdfWriter writer = new PdfWriter(byteArrayOutputStream);
     PdfDocument pdfDocument = new PdfDocument(writer);
     pdfDocument.SetDefaultPageSize(PageSize.A4.Rotate());
     HtmlConverter.ConvertToPdf(stream, pdfDocument);
     int pageCount = pdfDocument.GetNumberOfPages();
     for (int i = 1; i <= pageCount; i++)
     {
         Document doc = new Document(pdfDocument);
         doc.ShowTextAligned(new Paragraph("Page " + i + " of " + pageCount),
             pdfDocument.GetDefaultPageSize().GetWidth() - 50, 30, i, TextAlignment.RIGHT, VerticalAlignment.BOTTOM, 0);
     }
     pdfDocument.Close();
     return File(byteArrayOutputStream.ToArray(), "application/pdf", "AssetTaggingDetails.pdf");
 }
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,166 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,255 questions
{count} votes