Converting HTML to PDF in C# is a common requirement for many applications. iText7 is a powerful library that allows you to create
and manipulate PDF documents. It also supports converting HTML to PDF, making it an excellent choice.
Open Microsoft Visual Studio 2022. Create a Console application with .Net 8 and add the code below.
using iText.Html2pdf;
class Program
{
static void Main(string[] args)
{
string html = "<html><body><h1>HTML to Pdf</h1><div>This is an example to convert Html to Pdf file using itext7 in C#</div></body></html>";
string outputPath = "C:\\Pdf\\output.pdf";
using (FileStream outputStream = new FileStream(outputPath, FileMode.Create))
{
ConverterProperties converterProperties = new ConverterProperties();
HtmlConverter.ConvertToPdf(html, outputStream, converterProperties);
}
Console.WriteLine("HTML to PDF conversion completed successfully and pdf file create at C:\\Pdf.");
}
}
The above code converts html to pdf file using HtmlConverter.ConvertToPdf method —the HtmlConverter.ConvertToPdf method is used to convert the HTML file to a PDF document. The ConverterProperties object can be used to customize the conversion process if needed.
iText7 provides a straightforward way to convert HTML to PDF in C#. Following the steps above, we can easily integrate this functionality into your
C# applications.
This library offers extensive features and customization options, making it a versatile choice for PDF generation.