ahmed salah

ahmed salah

  • 1.2k
  • 547
  • 62.5k

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

Mar 26 2024 10:17 AM

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");
 }

 


Answers (1)