HTML String to PDF

With IronPDF, you can create new PDF documents from simple HTML strings within your .NET project, and IronPDF is able to be used in C#, F#, and VB.NET. Thanks to the use of the ChromePdfRenderer class, you can be sure that any PDF documents you render from HTML string will come out pixel-perfect. With IronPDF's powerful HTML to PDF conversion features, you create high-quality PDF files tailored to fit your personal needs.

The 4 Steps to Converting HTML String to PDF

  1. Import the IronPDF library
  2. Initialize a new ChromePdfRenderer Object.
  3. Use the ChromePdfRenderer.RenderHtmlAsPdf method.
  4. Save the PDF using PdfDocument.SaveAs.

See the code example below for more details:

using IronPdf;
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");
var myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", @"C:\site\assets\");
pdf.SaveAs("output.pdf");
using IronPdf;
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");
var myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", @"C:\site\assets\");
pdf.SaveAs("output.pdf");
Imports IronPdf
Private renderer = New ChromePdfRenderer()
Private pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>")
Private myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", "C:\site\assets\")
pdf.SaveAs("output.pdf")
VB   C#

The first step to converting HTML string to PDF in C# is ensuring that you have the IronPDF library properly set up and working within your project. By including using IronPdf, we are making sure we can access the classes needed from the IronPDF library to carry out HTML to PDF conversion. Once this is done, the next line, Installation.EnableWebSecurity = true is used to disable local disk access or cross-origin requests, ensuring secure operations.

This next line creates a new ChromePdfRenderer instance, which will handle the conversion of HTML to PDF. In the basic example, the RenderHtmlAsPdf method is used to convert a simple HTML string ("<h1>Hello World</h1>") into a PDF document, which is saved to the disk using the SaveAs method.

In the advanced method, we demonstrate how IronPDF can handle HTML content containing external assets such as images, CSS, and JavaScript. To load these assets, the optional BasePath parameter is used, which specifies the directory containing the required files. The resulting PDF, which includes the external assets, is saved using the same SaveAs method as seen in the basic example. This code example highlights IronPDF's ability to handle both basic and complex HTML content, making it an efficient tool for generating PDFs programmatically.

For more examples, check the How-to Guide on using IronPDF with C#.