How to Convert HTML to PDF and Add Custom Headers and Footers in .NET?
The Syncfusion® HTML-to-PDF converter is a robust .NET library designed to convert HTML, SVG, MHTML, and web pages into high-quality PDF documents using C#. Leveraging the Blink rendering engine (the same engine behind Google Chrome), it delivers precise rendering of text, images, fonts, and layouts.
This article explains how to convert HTML to PDF with Syncfusion’s .NET PDF library while adding custom headers and footers to specific pages. You’ll learn how to control page margins, set viewport sizes, and programmatically insert headers and footers only on selected pages giving you full flexibility over your PDF output.
Steps to convert HTML to PDF and add custom headers and footers
- Create a New Project: Start a new Console application in .NET Core to facilitate the HTML-to-PDF conversion process.
- Install Required Packages: Add the Syncfusion.HtmlToPdfConverter.Net.Windows NuGet package from Nuget.org to your project.
- Set Up Your Environment: In the
Program.csfile, include these namespaces.
C#
using Syncfusion.Drawing;
using Syncfusion.HtmlConverter;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Parsing;
- Apply Custom Headers and Footers: Follow these steps to convert HTML to PDF with conditional headers and footers
C#
// Initialize HTML to PDF converter
HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter();
//Convert the HTML to PDF without margins.
BlinkConverterSettings settings = new BlinkConverterSettings();
settings.Margin.All = 0;
settings.ViewPortSize = new Size(1024, 768); // Set the viewport size for rendering
htmlConverter.ConverterSettings = settings;
// Load HTML content from a file
string html = File.ReadAllText(Path.GetFullPath(@"Data/Sample.html"));
// Convert HTML to PDF
using (PdfDocument document = htmlConverter.Convert(html, ""))
{
if (Directory.Exists("Output") == false)
{
Directory.CreateDirectory("Output");
}
using (FileStream fileStream = new FileStream(Path.GetFullPath(@"Output/Output-HTML-To-PDF.pdf"), FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
// Save the converted PDF document
document.Save(fileStream);
}
}
htmlConverter.Close();
// Load the source
using (FileStream inputStream = new FileStream(Path.GetFullPath(@"Output/Output-HTML-To-PDF.pdf"), FileMode.Open, FileAccess.Read))
{
//Load the converted document
using (PdfLoadedDocument loadedDocument = new PdfLoadedDocument(inputStream))
{
// Define pages requiring headers
HashSet<int> pagesWithHeaders = new HashSet<int> { 0, 2 }; // 0-based: pages 1 and 3
// Create a new PDF document
using (PdfDocument finalDocument = new PdfDocument())
{
// Create a section for the new document
PdfSection section = finalDocument.Sections.Add();
// Set margins for the section
section.PageSettings.Margins.All = 0;
// Iterate over each page in the original document
for (int i = 0; i < loadedDocument.Pages.Count; i++)
{
bool hasHeaderAndFooter = pagesWithHeaders.Contains(i);
if (hasHeaderAndFooter)
{
// Set the page size to match the original document by allocating space for headers and footer.
section.PageSettings.Size = loadedDocument.Pages[i].Size;
}
else
{
// Set the page size to match the original document
section.PageSettings.Size = loadedDocument.Pages[i].Size;
}
// Create a new page in the final document
PdfPage destPage = section.Pages.Add();
// Copy content from the loaded document
PdfTemplate contentTemplate = loadedDocument.Pages[i].CreateTemplate();
if (hasHeaderAndFooter)
{
//Define the font for header
PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 12);
//Draw header and footer
AddHeaderAndFooter(destPage, "PDF Page Header Content", "PDF Page Footer Content", font);
//Draw the template
destPage.Graphics.DrawPdfTemplate(contentTemplate, new PointF(0, 50)); //50 Header height
}
else
{
// Draw the content on the destination page
destPage.Graphics.DrawPdfTemplate(contentTemplate, new PointF(0, 0));
}
}
using (FileStream fileStream1 = new FileStream(Path.GetFullPath(@"Output/Output-With-HeaderAndFooter.pdf"), FileMode.Create, FileAccess.ReadWrite))
{
// Save the converted PDF document
finalDocument.Save(fileStream1);
}
}
}
}
Add the following method to create headers and footers on the selected pages.
static void AddHeaderAndFooter(PdfPage page, string headerText, string footerText, PdfFont font)
{
// Draw header
page.Graphics.DrawLine(PdfPens.Gray, new PointF(0, 50), new PointF(page.GetClientSize().Width, 50));
//Measure the header text
SizeF textSize = font.MeasureString(headerText);
page.Graphics.DrawString(headerText, font, PdfBrushes.Red, new PointF((page.GetClientSize().Width - textSize.Width) / 2, (50 - textSize.Height) / 2));
// Draw footer
page.Graphics.DrawLine(PdfPens.Gray, new PointF(0, page.GetClientSize().Height - 50), new PointF(page.GetClientSize().Width, page.GetClientSize().Height - 50));
page.Graphics.DrawString(footerText, font, PdfBrushes.Green, new PointF(10, page.GetClientSize().Height - 50)); //50 Footer height
}
A complete working sample can be downloaded from GitHub.
By executing the program, you will generate the following PDF document.
Conclusion
I hope you enjoyed learning how to convert HTML to PDF and add custom headers and footers in .NET.
You can refer to our ASP.NET Core PDF feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our ASP.NET Core PDF example to understand how to create and manipulate data.
For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our other controls.
If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!