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");
}
Naimish MakwanaPosted Mar 26, 2024, 11:05 AM
The error you’re encountering is because the
pdfDocumentis closed as soon asHtmlConverter.ConvertToPdf(stream, pdfDocument);is executed. This makes it impossible to add more content (like page numbers) to the document afterwards.To solve this, you need to create a
PdfPageEventto add the page numbers after the conversion. Here’s how you can modify your code:This code creates a custom event handler
TextFooterEventHandlerthat adds a footer to each page when the page is completed. This way, the page numbers are added after the HTML is converted to PDF. Please replace"Page " + pageNumwith your desired footer text. The20inpageSize.GetBottom() + 20is the offset from the bottom of the page, adjust as needed. TheTextAlignment.CENTERaligns the text to the center, change it toTextAlignment.RIGHTif you want the text aligned to the right.Please note that you might need to adjust the code to fit your specific needs. Also, remember to handle exceptions and edge cases as necessary.
Thanks