Test in production without watermarks.
Works wherever you need it to.
Get 30 days of fully functional product.
Have it up and running in minutes.
Full access to our support engineering team during your product trial
Converting HTML to PDF is a common requirement in many software applications, such as generating reports, invoices, or saving web pages as PDFs. In this article, we'll explore three popular open-source libraries for HTML to PDF conversion in C#, review their strengths and limitations, and discuss why IronPDF is a better alternative in numerous instances.
Add from PixabayUpload
or drag and drop an image here
Add image alt text
PuppeteerSharp is a .NET wrapper for Puppeteer, a headless Chromium browser. It enables developers to convert HTML documents to PDFs by leveraging the Chromium rendering engine.
PuppeteerSharp provides precise control over the rendering process. Here's an example:
using PuppeteerSharp;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// Download Chromium
await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultChromiumRevision);
// Launch Browser
using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))
{
// Open a new page
var page = await browser.NewPageAsync();
// Set HTML content
await page.SetContentAsync("<html><body><h1>Hello, PuppeteerSharp!</h1></body></html>");
// Generate PDF
await page.PdfAsync("output.pdf");
Console.WriteLine("PDF Generated Successfully!");
}
}
}
using PuppeteerSharp;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// Download Chromium
await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultChromiumRevision);
// Launch Browser
using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true }))
{
// Open a new page
var page = await browser.NewPageAsync();
// Set HTML content
await page.SetContentAsync("<html><body><h1>Hello, PuppeteerSharp!</h1></body></html>");
// Generate PDF
await page.PdfAsync("output.pdf");
Console.WriteLine("PDF Generated Successfully!");
}
}
}
Imports PuppeteerSharp
Imports System.Threading.Tasks
Friend Class Program
Shared Async Function Main(ByVal args() As String) As Task
' Download Chromium
Await (New BrowserFetcher()).DownloadAsync(BrowserFetcher.DefaultChromiumRevision)
' Launch Browser
Using browser = Await Puppeteer.LaunchAsync(New LaunchOptions With {.Headless = True})
' Open a new page
Dim page = Await browser.NewPageAsync()
' Set HTML content
Await page.SetContentAsync("<html><body><h1>Hello, PuppeteerSharp!</h1></body></html>")
' Generate PDF
Await page.PdfAsync("output.pdf")
Console.WriteLine("PDF Generated Successfully!")
End Using
End Function
End Class
Download Chromium: PuppeteerSharp automatically downloads the required Chromium version to ensure compatibility.
Launch Browser: Start a headless instance of Chromium using Puppeteer.LaunchAsync().
Set HTML Content: Load the desired HTML into the browser page using page.SetContentAsync().
The result is a high-quality PDF (output.pdf) that accurately replicates the HTML structure and design.
Add from PixabayUpload
or drag and drop an image here
Add image alt text
PdfSharp is a powerful open-source library for creating and manipulating PDF files in C#. While it doesn't directly support HTML rendering, it excels at providing developers with tools to generate and edit PDF documents programmatically.
PDF Creation: PdfSharp allows developers to generate new PDF files from scratch by defining page sizes, adding text, shapes, images, and more.
Manipulation of Existing PDFs: You can modify existing PDF documents, such as merging, splitting, or extracting content.
Drawing Capabilities: PdfSharp provides robust graphics capabilities for adding custom designs to PDF files using the XGraphics class.
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using HtmlAgilityPack;
class Program
{
static void Main(string[] args)
{
// Example HTML content
string htmlContent = "<html><body><h1>Hello, PdfSharp!</h1><p>This is an example of HTML to PDF.</p></body></html>";
// Parse HTML using HtmlAgilityPack (You need to add HtmlAgilityPack via NuGet)
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(htmlContent);
// Create a new PDF document
PdfDocument pdfDocument = new PdfDocument();
pdfDocument.Info.Title = "HTML to PDF Example";
// Add a new page to the document
PdfPage page = pdfDocument.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
XFont titleFont = new XFont("Arial", 20, XFontStyle.Bold);
XFont textFont = new XFont("Arial", 12, XFontStyle.Regular);
// Draw the parsed HTML content
int yPosition = 50; // Starting Y position
foreach (var node in htmlDoc.DocumentNode.SelectNodes("//h1 | //p"))
{
if (node.Name == "h1")
{
gfx.DrawString(node.InnerText, titleFont, XBrushes.Black, new XRect(50, yPosition, page.Width - 100, page.Height - 100), XStringFormats.TopLeft);
yPosition += 30; // Adjust spacing
}
else if (node.Name == "p")
{
gfx.DrawString(node.InnerText, textFont, XBrushes.Black, new XRect(50, yPosition, page.Width - 100, page.Height - 100), XStringFormats.TopLeft);
yPosition += 20; // Adjust spacing
}
}
// Save the PDF document
string outputFilePath = "HtmlToPdf.pdf";
pdfDocument.Save(outputFilePath);
System.Console.WriteLine($"PDF file created: {outputFilePath}");
}
}
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using HtmlAgilityPack;
class Program
{
static void Main(string[] args)
{
// Example HTML content
string htmlContent = "<html><body><h1>Hello, PdfSharp!</h1><p>This is an example of HTML to PDF.</p></body></html>";
// Parse HTML using HtmlAgilityPack (You need to add HtmlAgilityPack via NuGet)
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(htmlContent);
// Create a new PDF document
PdfDocument pdfDocument = new PdfDocument();
pdfDocument.Info.Title = "HTML to PDF Example";
// Add a new page to the document
PdfPage page = pdfDocument.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
XFont titleFont = new XFont("Arial", 20, XFontStyle.Bold);
XFont textFont = new XFont("Arial", 12, XFontStyle.Regular);
// Draw the parsed HTML content
int yPosition = 50; // Starting Y position
foreach (var node in htmlDoc.DocumentNode.SelectNodes("//h1 | //p"))
{
if (node.Name == "h1")
{
gfx.DrawString(node.InnerText, titleFont, XBrushes.Black, new XRect(50, yPosition, page.Width - 100, page.Height - 100), XStringFormats.TopLeft);
yPosition += 30; // Adjust spacing
}
else if (node.Name == "p")
{
gfx.DrawString(node.InnerText, textFont, XBrushes.Black, new XRect(50, yPosition, page.Width - 100, page.Height - 100), XStringFormats.TopLeft);
yPosition += 20; // Adjust spacing
}
}
// Save the PDF document
string outputFilePath = "HtmlToPdf.pdf";
pdfDocument.Save(outputFilePath);
System.Console.WriteLine($"PDF file created: {outputFilePath}");
}
}
Imports PdfSharp.Pdf
Imports PdfSharp.Drawing
Imports HtmlAgilityPack
Friend Class Program
Shared Sub Main(ByVal args() As String)
' Example HTML content
Dim htmlContent As String = "<html><body><h1>Hello, PdfSharp!</h1><p>This is an example of HTML to PDF.</p></body></html>"
' Parse HTML using HtmlAgilityPack (You need to add HtmlAgilityPack via NuGet)
Dim htmlDoc = New HtmlDocument()
htmlDoc.LoadHtml(htmlContent)
' Create a new PDF document
Dim pdfDocument As New PdfDocument()
pdfDocument.Info.Title = "HTML to PDF Example"
' Add a new page to the document
Dim page As PdfPage = pdfDocument.AddPage()
Dim gfx As XGraphics = XGraphics.FromPdfPage(page)
Dim titleFont As New XFont("Arial", 20, XFontStyle.Bold)
Dim textFont As New XFont("Arial", 12, XFontStyle.Regular)
' Draw the parsed HTML content
Dim yPosition As Integer = 50 ' Starting Y position
For Each node In htmlDoc.DocumentNode.SelectNodes("//h1 | //p")
If node.Name = "h1" Then
gfx.DrawString(node.InnerText, titleFont, XBrushes.Black, New XRect(50, yPosition, page.Width - 100, page.Height - 100), XStringFormats.TopLeft)
yPosition += 30 ' Adjust spacing
ElseIf node.Name = "p" Then
gfx.DrawString(node.InnerText, textFont, XBrushes.Black, New XRect(50, yPosition, page.Width - 100, page.Height - 100), XStringFormats.TopLeft)
yPosition += 20 ' Adjust spacing
End If
Next node
' Save the PDF document
Dim outputFilePath As String = "HtmlToPdf.pdf"
pdfDocument.Save(outputFilePath)
System.Console.WriteLine($"PDF file created: {outputFilePath}")
End Sub
End Class
HTML Parsing: The example uses HtmlAgilityPack (an open-source library for parsing and manipulating HTML) to extract text content from
tags.
Drawing Content: PdfSharp's XGraphics class is used to render the parsed HTML content as text on a PDF page.
Add from PixabayUpload
or drag and drop an image here
Add image alt text
Pdfium.NET is a comprehensive library based on the open-source PDFium project, designed for viewing, editing, and manipulating PDF files in .NET applications. It provides developers with powerful tools to create, edit, and extract content from PDFs, making it suitable for a wide range of use cases. It is basically free HTML to PDF converter library.
PDF Creation and Editing:
Text and Image Extraction:
PDF Viewer Control:
Compatibility:
Advanced Features:
using Pdfium.Net.SDK;
using System;
class Program
{
static void Main(string[] args)
{
// Initialize Pdfium.NET SDK
PdfCommon.Initialize();
// Create a new PDF document
PdfDocument pdfDocument = PdfDocument.CreateNew();
// Add a page to the document
var page = pdfDocument.Pages.InsertPageAt(pdfDocument.Pages.Count, 595, 842); // A4 size in points (8.27 x 11.69 inches)
// Add HTML content (example: parsed manually)
var htmlContent = "<h1>Hello, Pdfium.NET SDK!</h1><p>This is an example of HTML to PDF.</p>";
// Example: Rendering text manually (since Pdfium.NET doesn't render HTML directly)
var font = PdfFont.CreateFont(pdfDocument, "Arial");
page.AddText(72, 750, font, 20, "Hello, Pdfium.NET SDK!");
page.AddText(72, 700, font, 14, "This is an example of HTML to PDF.");
// Save the document
string outputFilePath = "HtmlToPdfExample.pdf";
pdfDocument.Save(outputFilePath, SaveFlags.Default);
Console.WriteLine($"PDF created successfully: {outputFilePath}");
}
}
using Pdfium.Net.SDK;
using System;
class Program
{
static void Main(string[] args)
{
// Initialize Pdfium.NET SDK
PdfCommon.Initialize();
// Create a new PDF document
PdfDocument pdfDocument = PdfDocument.CreateNew();
// Add a page to the document
var page = pdfDocument.Pages.InsertPageAt(pdfDocument.Pages.Count, 595, 842); // A4 size in points (8.27 x 11.69 inches)
// Add HTML content (example: parsed manually)
var htmlContent = "<h1>Hello, Pdfium.NET SDK!</h1><p>This is an example of HTML to PDF.</p>";
// Example: Rendering text manually (since Pdfium.NET doesn't render HTML directly)
var font = PdfFont.CreateFont(pdfDocument, "Arial");
page.AddText(72, 750, font, 20, "Hello, Pdfium.NET SDK!");
page.AddText(72, 700, font, 14, "This is an example of HTML to PDF.");
// Save the document
string outputFilePath = "HtmlToPdfExample.pdf";
pdfDocument.Save(outputFilePath, SaveFlags.Default);
Console.WriteLine($"PDF created successfully: {outputFilePath}");
}
}
Imports Pdfium.Net.SDK
Imports System
Friend Class Program
Shared Sub Main(ByVal args() As String)
' Initialize Pdfium.NET SDK
PdfCommon.Initialize()
' Create a new PDF document
Dim pdfDocument As PdfDocument = PdfDocument.CreateNew()
' Add a page to the document
Dim page = pdfDocument.Pages.InsertPageAt(pdfDocument.Pages.Count, 595, 842) ' A4 size in points (8.27 x 11.69 inches)
' Add HTML content (example: parsed manually)
Dim htmlContent = "<h1>Hello, Pdfium.NET SDK!</h1><p>This is an example of HTML to PDF.</p>"
' Example: Rendering text manually (since Pdfium.NET doesn't render HTML directly)
Dim font = PdfFont.CreateFont(pdfDocument, "Arial")
page.AddText(72, 750, font, 20, "Hello, Pdfium.NET SDK!")
page.AddText(72, 700, font, 14, "This is an example of HTML to PDF.")
' Save the document
Dim outputFilePath As String = "HtmlToPdfExample.pdf"
pdfDocument.Save(outputFilePath, SaveFlags.Default)
Console.WriteLine($"PDF created successfully: {outputFilePath}")
End Sub
End Class
SDK Initialization: The PdfCommon.Initialize() method initializes Pdfium.NET functionalities.
Creating a PDF: A new PDF document is created using PdfDocument.CreateNew().
Adding Pages: Pages are inserted into the PDF with specified dimensions (e.g., A4 size).
Rendering HTML Content: Since Pdfium.NET SDK does not natively support HTML rendering, you need to manually parse and render HTML elements as text, shapes, or images.
Add from PixabayUpload
or drag and drop an image here
Add image alt text
IronPDF is a professional-grade library designed for .NET developers to effortlessly convert HTML content into high-quality PDFs. Known for its reliability, advanced features, and ease of use, IronPDF streamlines the development process while delivering precise rendering and robust functionality. Here’s why IronPDF is a standout solution:
Direct HTML to PDF Conversion: create PDF documents directly using IronPDF with HTML content, including CSS and JavaScript, into fully formatted PDFs. With just a few lines of code, developers can generate PDFs from web pages, raw HTML strings, or local HTML files.
Modern Rendering Capabilities: Supporting the latest web standards, IronPDF ensures accurate rendering of complex layouts, styles, and interactive elements to convert HTML pages to PDF.
Advanced PDF Features: IronPDF offers extensive customization options, such as adding headers, footers, watermarks, annotations, and bookmarks. It also supports merging, splitting, and editing existing PDFs. Split PDF documents,
Performance and Scalability: Optimized for both small-scale applications and enterprise environments, IronPDF delivers fast, reliable performance for projects of any size.
IronPDF stands out among other solutions due to its combination of features, developer support, and performance. Unlike open-source alternatives that often require extensive configuration or external dependencies, IronPDF is a self-contained solution that simplifies development without sacrificing functionality. Whether it's for generating invoices, reports, or archiving web content, IronPDF empowers developers with the tools they need to achieve professional-grade results quickly and efficiently.
IronPDF is a practical choice for developers who value reliability, scalability, and ease of use in their HTML to PDF workflows
class Program
{
static void Main()
{
// Specify license key
License.LicenseKey = "Yoour Key";
// Create a new HtmlToPdf object
var Renderer = new ChromePdfRenderer();
// Define the HTML string/ HTML code to be converted, can use html document
string htmlContent = "<html><body><h1>IronPDF: Beter than Open source</h1></body></html>";
// Convert pdf simple HTML string to a PDF document
var document = Renderer.RenderHtmlAsPdf(htmlContent);
// Save the PDF output document to a file
document.SaveAs("html2Pdf.pdf"); // path to pdf file generated
}
}
class Program
{
static void Main()
{
// Specify license key
License.LicenseKey = "Yoour Key";
// Create a new HtmlToPdf object
var Renderer = new ChromePdfRenderer();
// Define the HTML string/ HTML code to be converted, can use html document
string htmlContent = "<html><body><h1>IronPDF: Beter than Open source</h1></body></html>";
// Convert pdf simple HTML string to a PDF document
var document = Renderer.RenderHtmlAsPdf(htmlContent);
// Save the PDF output document to a file
document.SaveAs("html2Pdf.pdf"); // path to pdf file generated
}
}
Friend Class Program
Shared Sub Main()
' Specify license key
License.LicenseKey = "Yoour Key"
' Create a new HtmlToPdf object
Dim Renderer = New ChromePdfRenderer()
' Define the HTML string/ HTML code to be converted, can use html document
Dim htmlContent As String = "<html><body><h1>IronPDF: Beter than Open source</h1></body></html>"
' Convert pdf simple HTML string to a PDF document
Dim document = Renderer.RenderHtmlAsPdf(htmlContent)
' Save the PDF output document to a file
document.SaveAs("html2Pdf.pdf") ' path to pdf file generated
End Sub
End Class
The program starts by setting the IronPDF license key, which is required to unlock the full functionality of the library.
An instance of ChromePdfRenderer is initialized. This component is responsible for converting HTML content into a PDF document, acting as a bridge between the raw HTML and the final output.
A string variable, htmlContent, is created to store the HTML structure that will be converted into a PDF. In this example, it contains a simple heading.
The RenderHtmlAsPdf() method is called on the ChromePdfRenderer instance, passing the HTML string as input. This function processes the content and transforms it into a PDF document.
Finally, the generated PDF is saved to a file named "html2Pdf.pdf" using the SaveAs() method, storing it on the disk for future access.
Add from PixabayUpload
or drag and drop an image here
Add image alt text
IronPDF requires a valid license key for full functionality. You can obtain a trial license from the official website. Before using the IronPDF library, set the license key as follows:
IronPdf.License.LicenseKey = "your key";
IronPdf.License.LicenseKey = "your key";
IronPdf.License.LicenseKey = "your key"
This ensures that the library operates without limitations.
PuppeteerSharp is an excellent choice for developers who need precise rendering of HTML to PDF, especially when dealing with complex web pages. However, for applications that require advanced PDF-specific features, performance optimization, and ease of integration, professional tools like IronPDF are often the better option.
PdfSharp is a great choice for lightweight, programmatic PDF creation and manipulation, especially for projects with simple requirements. However, if your application requires converting HTML to PDF or advanced PDF features, IronPDF provides a more efficient and feature-rich solution.
While Pdfium.NET SDK is a robust tool for PDF manipulation, IronPDFprovides native support for direct HTML-to-PDF conversion, including rendering modern HTML, CSS, and JavaScript. IronPDF simplifies the workflow with built-in methods like HtmlToPdf.RenderHtmlAsPdf(), making it faster and more efficient for developers.
Whether it's for generating invoices, reports, or archiving web content, IronPDF empowers developers with the tools they need to achieve professional-grade results quickly and efficiently.
IronPDF is a practical choice for developers who value reliability, scalability, and ease of use in their HTML to PDF workflows