private byte[] GeneratePdf(string htmlString) { using (var memoryStream = new MemoryStream()) { var converterProperties = new iText.Html2pdf.ConverterProperties(); string basePath = AppDomain.CurrentDomain.BaseDirectory; converterProperties.SetBaseUri(basePath); using (var htmlStream = new MemoryStream(Encoding.UTF8.GetBytes(htmlString))) { HtmlConverter.ConvertToPdf(htmlStream, memoryStream, converterProperties); } return memoryStream.ToArray(); } }
Loading
Vinay SinghPosted Jan 31, 2025, 6:56 PM
Hi
try the below link
https://stackoverflow.com/questions/71574403/add-header-and-footer-on-all-pdf-pages-using-itext7-pdfhtml https://stackoverflow.com/questions/64486650/itext-7-add-header-and-footer-in-html-to-pdf/64486858#64486858
Thanks
Vinay(Codemantra99.com)
Tuhin PaulPosted Jan 31, 2025, 5:04 AM
Part -2
Customization
You can customize the header and footer text, font, size, and position by modifying the
HeaderFooterEventHandlerclass.For example, you can add a logo or dynamic content (e.g., date/time) to the header or footer.
Explaination of the process as shown below:
Tuhin PaulPosted Jan 31, 2025, 5:02 AM
Part -1
To add a header and footer to a PDF generated using iText7, you can use the
PdfPageEventHelperclass. This class allows you to define custom behaviour for events like adding content to a page (e.g., headers and footers).Updated Code with Header and Footer
Explanation of the Code
HeaderFooterEventHandler Class:
This class implements the
IEventHandlerinterface to handle page events.The
HandleEventmethod is triggered for each page, allowing you to add custom content (header and footer).Header:
The header is added at the top of each page using
canvas.BeginText()andShowText().The position is set using
xandycoordinates.Footer:
The footer is added at the bottom of each page.
The page number is dynamically added using
pdf.GetPageNumber(page).Adding the Event Handler:
The
HeaderFooterEventHandleris registered usingpdf.AddEventHandler().It listens for the
START_PAGEevent to add the header and footer before the page content is written.Generating the PDF:
The
HtmlConverter.ConvertToPdf()method converts the HTML to PDF.The header and footer are automatically added to each page.
Sample code:
Output
The generated PDF will have a header ("This is the Header") at the top of each page.
The footer will display the page number (e.g., "Page 1", "Page 2", etc.) at the bottom of each page.