USING IRON SUITE

HTML to PDF in C# for .NET Developers (The Ultimate Guide)

Introduction

In today's web-driven world, the ability to convert HTML content into PDF documents (Portable Document Format) is a crucial feature for many applications. Whether it's for generating PDF files from reports, invoices, or archiving web content, HTML to PDF conversion streamlines workflows and ensures consistent formatting of high-quality PDFs. Libraries like IronPDF provide a developer-friendly way to handle this conversion, supporting dynamic content, HTML forms, and precise rendering of CSS and JavaScript.

For .NET developers, using the right HTML to PDF converter impacts efficiency, code simplicity, and PDF generation quality. Modern libraries allow developers to directly convert HTML strings, entire web pages, or HTML files into rendered PDF documents in just a few lines of code, enabling dynamic documents, custom headers, and printable versions of web content.

What You’ll Learn

In this guide, you'll learn how to convert HTML to PDF in C# across several libraries and explore their PDF conversion capabilities, including manipulating PDF documents, HTML forms, custom margins, and secure PDFs. The topics we'll be covering in this article are:

  1. Why Compare HTML to PDF Tools?
  2. IronPDF: HTML to PDF Conversion
  3. Aspose: HTML to PDF Conversion
  4. iText 9: HTML to PDF Conversion
  5. wkhtmltopdf: HTML to PDF Conversion
  6. PuppeteerSharp: HTML to PDF Conversion
  7. Conclusion Why Choose IronPDF?

By the end, you'll understand why IronPDF stands out as a developer-friendly and efficient HTML to PDF converter. Be sure to check out our other comparison guides, where we take a deeper look at how IronPDF compares with, Aspose.PDF, iText 9, wkhtmltopdf, and PuppeteerSharp to see which fits your project best, and why IronPDF comes out on top.

Why Compare HTML to PDF Tools?

Selecting the appropriate HTML to PDF conversion tool is essential for ensuring that your application meets performance, quality, and cost requirements. With numerous options available, each offering different PDF conversion capabilities, a thorough comparison helps in making an informed decision. Here are the key evaluation criteria to consider:

  • Integration Complexity: How easily the library integrates with your existing .NET projects, such as using the NuGet package Manager for simple installation and API integration tab setup.
  • Code Simplicity: The ease of writing and maintaining source code, including minimal code examples like just a few lines to convert HTML strings or entire web pages to generated PDF documents.
  • Rendering Accuracy: The ability of the rendering engine to accurately handle HTML code, JavaScript execution, print CSS, HTML forms, and other dynamic content while producing high-quality PDFs.
  • Performance at Scale: How well the PDF converter performs under heavy load when generating PDF files from multiple HTML pages or dynamic content.
  • Licensing and Cost-Effectiveness: The pricing models, such as commercial license, and suitability for your project's budget.

By assessing these factors, developers can choose a tool that fits both technical requirements and financial constraints, whether working with .NET Core or .NET Framework projects in Visual Studio.

IronPDF: HTML to PDF Conversion

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 1

IronPDF is a full-featured .NET library designed specifically for developers. It provides out-of-the-box methods for converting HTML strings, local files, and live URLs into PDFs with minimal setup. Its Chrome-based rendering engine ensures high accuracy, including support for CSS and JavaScript. IronPDF is commercial but offers strong support and a straightforward API.

HTML String to PDF

Converting HTML from a string to a PDF is simple with IronPDF. This approach is ideal for dynamic content generation or small HTML snippets.

Example:

using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>");
        pdf.SaveAs("output.pdf");
    }
}
using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>");
        pdf.SaveAs("output.pdf");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Generated PDF Document

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 2

Explanation:

  1. ChromePdfRenderer: The ChromePdfRenderer class is the primary tool for converting HTML to PDF in IronPDF. It comes pre-configured to handle most use cases with minimal setup.
  2. RenderHtmlAsPdf: This method takes an HTML string as input and generates a PDF document.
  3. SaveAs: The generated PDF is saved to the specified path (output.pdf).

Local HTML File to PDF

For applications that need to convert a local HTML file (with external resources like CSS or JavaScript), IronPDF makes it easy.

Example:

using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        PdfDocument pdf = renderer.RenderHtmlFileAsPdf("template.html");
        pdf.SaveAs("report.pdf");
    }
}
using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        PdfDocument pdf = renderer.RenderHtmlFileAsPdf("template.html");
        pdf.SaveAs("report.pdf");
    }
}
Imports IronPdf
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()
		Dim pdf As PdfDocument = renderer.RenderHtmlFileAsPdf("template.html")
		pdf.SaveAs("report.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

Input HTML File

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 3

Output

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 4

Explanation:

  • RenderHtmlFileAsPdf: Takes a local HTML file and converts it into a PDF.
  • Handles linked resources automatically, such as external CSS and JavaScript files.

URL to PDF

IronPDF is especially powerful when converting dynamic web content from URLs, including pages that use JavaScript.

Example:

using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        renderer.RenderingOptions.EnableJavaScript = true;
        renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;
        renderer.RenderingOptions.WaitFor.RenderDelay(3000); // Wait up to 3 seconds for JS to load

        PdfDocument pdf = renderer.RenderUrlAsPdf("https://apple.com");
        pdf.SaveAs("url-to-pdf.pdf");
    }
}
using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        renderer.RenderingOptions.EnableJavaScript = true;
        renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;
        renderer.RenderingOptions.WaitFor.RenderDelay(3000); // Wait up to 3 seconds for JS to load

        PdfDocument pdf = renderer.RenderUrlAsPdf("https://apple.com");
        pdf.SaveAs("url-to-pdf.pdf");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Output

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 5

Explanation:

  • RenderUrlAsPdf: Fetches the URL content, including JavaScript-rendered elements, and converts it to PDF.

Verdict / When to Use

IronPDF is perfect for developers who need easy API integration, minimal code, and support for manipulating PDF documents, creating dynamic documents, HTML forms, custom headers, and printable versions of web content. Ideal for .NET Core or .NET Framework projects in Visual Studio.

Aspose: HTML to PDF Conversion

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 6

Aspose.PDF is another powerful library for PDF manipulation, with support for converting HTML to PDF. Let’s see how Aspose handles each conversion scenario:

HTML String to PDF

Aspose requires a bit more setup when converting HTML strings compared to IronPDF.

Example:

using Aspose.Html;
using Aspose.Html.Saving;

Document doc = new Document();
Page page = doc.getPages().Add();
HtmlFragment htmlFragment = new HtmlFragment("<h1>HTML String</h1>");
page.getParagraphs().Add(htmlFragment);
doc.Save("HTMLStringUsingDOM.pdf");
using Aspose.Html;
using Aspose.Html.Saving;

Document doc = new Document();
Page page = doc.getPages().Add();
HtmlFragment htmlFragment = new HtmlFragment("<h1>HTML String</h1>");
page.getParagraphs().Add(htmlFragment);
doc.Save("HTMLStringUsingDOM.pdf");
Imports Aspose.Html
Imports Aspose.Html.Saving

Private doc As New Document()
Private page As Page = doc.getPages().Add()
Private htmlFragment As New HtmlFragment("<h1>HTML String</h1>")
page.getParagraphs().Add(htmlFragment)
doc.Save("HTMLStringUsingDOM.pdf")
$vbLabelText   $csharpLabel

Output

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 7

Explanation:

  • Document doc: Creates a new document to save the converted HTML string to.
  • Page page: This line adds a new page to the empty document we created.
  • HtmlFragment htmlFragment: This is the HTML string we are converting.
  • page.getParagraphs().Add(htmlFragment): Add the HTML to the document.
  • doc.Save: Saves the document with the HTML content as a PDF document.

Local HTML File to PDF

Aspose also handles converting local HTML files to PDFs, but it requires more configuration than IronPDF.

Example:

using Aspose.Html;
using Aspose.Html.Converters;
using Aspose.Html.Saving;

var document = new HTMLDocument("document.html");
var options = new PdfSaveOptions();
Converter.ConvertHTML(document, options, "output.pdf");
using Aspose.Html;
using Aspose.Html.Converters;
using Aspose.Html.Saving;

var document = new HTMLDocument("document.html");
var options = new PdfSaveOptions();
Converter.ConvertHTML(document, options, "output.pdf");
Imports Aspose.Html
Imports Aspose.Html.Converters
Imports Aspose.Html.Saving

Private document = New HTMLDocument("document.html")
Private options = New PdfSaveOptions()
Converter.ConvertHTML(document, options, "output.pdf")
$vbLabelText   $csharpLabel

Input HTML:

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 8

Output:

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 9

Explanation:

  • var document = new HTMLDocument("document.html"): Loads the HTML file.
  • var options: Creates a new PdfSaveOptions object.
  • Converter.ConvertHTML(): Converts the HTML to PDF.

URL to PDF

Aspose provides similar functionality for URLs but requires extra setup.

Example:

using System.IO;
using System;
using System.Net.Http;
using Aspose.Pdf;

HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("https://www.apple.com");
response.EnsureSuccessStatusCode();
string responseFromServer = await response.Content.ReadAsStringAsync();
MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseFromServer));
HtmlLoadOptions options = new HtmlLoadOptions("https://www.apple.com");
Document pdfDocument = new Document(stream, options);
pdfDocument.Save("WebPageToPDF_out.pdf");
using System.IO;
using System;
using System.Net.Http;
using Aspose.Pdf;

HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("https://www.apple.com");
response.EnsureSuccessStatusCode();
string responseFromServer = await response.Content.ReadAsStringAsync();
MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseFromServer));
HtmlLoadOptions options = new HtmlLoadOptions("https://www.apple.com");
Document pdfDocument = new Document(stream, options);
pdfDocument.Save("WebPageToPDF_out.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Output

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 10

Explanation:

  • The dataDir variable holds the directory where the generated PDF will be saved.
  • A WebRequest is created to access the Wikipedia main page URL, and default credentials are used for the request.
  • The GetResponse() method sends the request and retrieves the response as an HttpWebResponse.
  • A stream is obtained from the response, and a StreamReader reads the entire HTML content of the page into the responseFromServer string.
  • The HTML content from responseFromServer is converted into a byte array and then loaded into a MemoryStream.
  • HtmlLoadOptions is used to specify the base URL for relative links and other settings.
  • An Aspose.Pdf.Document is created from the memory stream containing the HTML, and the document is saved as a PDF to the specified directory.

Verdict / When to Use

Aspose.PDF is best for enterprise projects that require advanced PDF manipulation as well as conversion. It’s powerful but less streamlined for quick HTML-to-PDF tasks.

iText 9: HTML to PDF Conversion

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 11

iText 9 is the latest iteration of the iText PDF library, offering enhanced features for generating and manipulating PDF documents in .NET applications. It introduces a more streamlined and extensible API, improving performance and providing better support for modern PDF standards.

HTML String to PDF

Here's a basic example of how to convert an HTML string to a PDF document using iText 9.

Example:

using iText.Html2pdf;
using System.IO;

class Program
{
    static void Main()
    {
        string html = "<h1>Hello World</h1><p>This is a simple PDF generated from HTML.</p>";
        string outputFile = "SimpleHtmlToPdf.pdf";

        using (var pdfStream = new FileStream(outputFile, FileMode.Create))
        {
            HtmlConverter.ConvertToPdf(html, pdfStream);
        }

        System.Console.WriteLine("PDF generated: " + outputFile);
    }
}
using iText.Html2pdf;
using System.IO;

class Program
{
    static void Main()
    {
        string html = "<h1>Hello World</h1><p>This is a simple PDF generated from HTML.</p>";
        string outputFile = "SimpleHtmlToPdf.pdf";

        using (var pdfStream = new FileStream(outputFile, FileMode.Create))
        {
            HtmlConverter.ConvertToPdf(html, pdfStream);
        }

        System.Console.WriteLine("PDF generated: " + outputFile);
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Output

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 12

Local HTML File to PDF

iText 9 can convert HTML file types to PDF using the HtmlConverter.ConvertToPdf class.

Example:

using iText.Html2pdf;
using System.IO;

class Program
{
    static void Main()
    {
        string htmlFile = "document.html";
        string outputPdf = "html-file-to-pdf.pdf";

        // Read HTML content from file
        string htmlContent = File.ReadAllText(htmlFile);

        // Convert HTML string to PDF
        HtmlConverter.ConvertToPdf(htmlContent, new FileStream(outputPdf, FileMode.Create));

        System.Console.WriteLine("PDF generated: " + outputPdf);
    }
}
using iText.Html2pdf;
using System.IO;

class Program
{
    static void Main()
    {
        string htmlFile = "document.html";
        string outputPdf = "html-file-to-pdf.pdf";

        // Read HTML content from file
        string htmlContent = File.ReadAllText(htmlFile);

        // Convert HTML string to PDF
        HtmlConverter.ConvertToPdf(htmlContent, new FileStream(outputPdf, FileMode.Create));

        System.Console.WriteLine("PDF generated: " + outputPdf);
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Output

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 13

Explanation:

  • HtmlConverter: Converts an HTML file directly to a PDF.

URL to PDF

iText7 also supports converting content from URLs.

Example:

using iText.Html2pdf;
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        string url = "https://apple.com";
        string outputPdf = "url-to-pdf.pdf";

        using var httpClient = new HttpClient();
        // Fetch the HTML content from the URL
        string htmlContent = await httpClient.GetStringAsync(url);

        // Convert HTML content to PDF
        HtmlConverter.ConvertToPdf(htmlContent, new FileStream(outputPdf, FileMode.Create));

        Console.WriteLine("PDF generated: " + outputPdf);
    }
}
using iText.Html2pdf;
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        string url = "https://apple.com";
        string outputPdf = "url-to-pdf.pdf";

        using var httpClient = new HttpClient();
        // Fetch the HTML content from the URL
        string htmlContent = await httpClient.GetStringAsync(url);

        // Convert HTML content to PDF
        HtmlConverter.ConvertToPdf(htmlContent, new FileStream(outputPdf, FileMode.Create));

        Console.WriteLine("PDF generated: " + outputPdf);
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Output

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 14

Explanation:

  • HttpClient.GetStringAsync(url): Downloads the actual HTML content from the URL.
  • HtmlConverter.ConvertToPdf(htmlContent, …): Converts the fetched HTML string into a rendered PDF.

Verdict / When to Use

iText 9 is suitable for developers who need a robust, enterprise-grade solution for PDF creation, manipulation, and HTML-to-PDF conversion. It works well when you require precise control over the generated PDF, integration with existing iText workflows, or advanced PDF features like digital signatures and forms. However, for simple HTML-to-PDF tasks, iText 9 is heavier and more complex than streamlined libraries like IronPDF.

wkhtmltopdf: HTML to PDF Conversion

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 15

Archive & Maintenance Status

It's important to note that wkhtmltopdf is no longer actively maintained. Its GitHub repository was officially archived in January 2023 and marked read-only, which means no future updates, bug fixes, or security patches are being applied.

Implication for developers: While wkhtmltopdf can still be effective for very basic use cases, its unmaintained status and outdated rendering engine make it a risky choice—especially for production environments or applications handling dynamic or external HTML content.

wkhtmltopdf is a command-line tool that converts HTML files to PDF using Webkit rendering. Here’s how it works for different scenarios:

HTML String to PDF

wkhtmltopdf requires converting HTML strings by writing them to a file first.

Example:

using System;
using System.IO;
using System.Diagnostics;
class Program
{
    static void Main(string[] args)
    {
        // HTML string to be converted to PDF
        string html = "<html><body><h1>Hello, World!</h1></body></html>";
        // Write HTML string to temporary file
        string tempHtmlFile = Path.Combine(Path.GetTempPath(), "temp.html");
        File.WriteAllText(tempHtmlFile, html);
        // Set output PDF path
        string outputPdfFile = Path.Combine(Path.GetTempPath(), "html-string-to-pdf.pdf");
        // Execute wkhtmltopdf command
        Process process = new Process();
        process.StartInfo.FileName = "wkhtmltopdf";
        process.StartInfo.Arguments = $"\"{tempHtmlFile}\" \"{outputPdfFile}\"";
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.Start();
        process.WaitForExit();
        // Clean up the temporary HTML file
        File.Delete(tempHtmlFile);
        Console.WriteLine($"PDF saved to: {outputPdfFile}");
    }
}
using System;
using System.IO;
using System.Diagnostics;
class Program
{
    static void Main(string[] args)
    {
        // HTML string to be converted to PDF
        string html = "<html><body><h1>Hello, World!</h1></body></html>";
        // Write HTML string to temporary file
        string tempHtmlFile = Path.Combine(Path.GetTempPath(), "temp.html");
        File.WriteAllText(tempHtmlFile, html);
        // Set output PDF path
        string outputPdfFile = Path.Combine(Path.GetTempPath(), "html-string-to-pdf.pdf");
        // Execute wkhtmltopdf command
        Process process = new Process();
        process.StartInfo.FileName = "wkhtmltopdf";
        process.StartInfo.Arguments = $"\"{tempHtmlFile}\" \"{outputPdfFile}\"";
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.Start();
        process.WaitForExit();
        // Clean up the temporary HTML file
        File.Delete(tempHtmlFile);
        Console.WriteLine($"PDF saved to: {outputPdfFile}");
    }
}
Imports System
Imports System.IO
Imports System.Diagnostics
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' HTML string to be converted to PDF
		Dim html As String = "<html><body><h1>Hello, World!</h1></body></html>"
		' Write HTML string to temporary file
		Dim tempHtmlFile As String = Path.Combine(Path.GetTempPath(), "temp.html")
		File.WriteAllText(tempHtmlFile, html)
		' Set output PDF path
		Dim outputPdfFile As String = Path.Combine(Path.GetTempPath(), "html-string-to-pdf.pdf")
		' Execute wkhtmltopdf command
		Dim process As New Process()
		process.StartInfo.FileName = "wkhtmltopdf"
		process.StartInfo.Arguments = $"""{tempHtmlFile}"" ""{outputPdfFile}"""
		process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
		process.Start()
		process.WaitForExit()
		' Clean up the temporary HTML file
		File.Delete(tempHtmlFile)
		Console.WriteLine($"PDF saved to: {outputPdfFile}")
	End Sub
End Class
$vbLabelText   $csharpLabel

Output

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 16

Explanation:

  • wkhtmltopdf requires an input file, so we first write the HTML string to a temporary file (temp.html).
  • We then use the Process class to execute the wkhtmltopdf command, passing the file path of the temporary HTML file and the desired output PDF path as arguments.
  • After conversion, we delete the temporary HTML file to clean up.

Local HTML File to PDF

For converting a local HTML file to a PDF using wkhtmltopdf, you can directly point to the file path of the HTML file.

Example:

using System;
using System.Diagnostics;

class Program
{
    static void Main(string[] args)
    {
        // Path to the local HTML file
        string htmlFilePath = @"C:\path\to\your\document.html";
        // Path for the output PDF file
        string outputPdfFile = @"C:\path\to\output\html-file-to-pdf.pdf";
        // Execute wkhtmltopdf command
        Process process = new Process();
        process.StartInfo.FileName = "wkhtmltopdf";
        process.StartInfo.Arguments = $"\"{htmlFilePath}\" \"{outputPdfFile}\"";
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.Start();
        process.WaitForExit();
        Console.WriteLine($"PDF saved to: {outputPdfFile}");
    }
}
using System;
using System.Diagnostics;

class Program
{
    static void Main(string[] args)
    {
        // Path to the local HTML file
        string htmlFilePath = @"C:\path\to\your\document.html";
        // Path for the output PDF file
        string outputPdfFile = @"C:\path\to\output\html-file-to-pdf.pdf";
        // Execute wkhtmltopdf command
        Process process = new Process();
        process.StartInfo.FileName = "wkhtmltopdf";
        process.StartInfo.Arguments = $"\"{htmlFilePath}\" \"{outputPdfFile}\"";
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.Start();
        process.WaitForExit();
        Console.WriteLine($"PDF saved to: {outputPdfFile}");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Output

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 17

Explanation:

  • This example simply provides the path to the local HTML file (template.html) and the output path for the PDF.
  • wkhtmltopdf directly handles local files, making the command straightforward.

URL to PDF

Converting a URL to a PDF is easy with wkhtmltopdf. Just pass the URL directly to the command.

Example:

using System;
using System.Diagnostics;

class Program
{
    static void Main(string[] args)
    {
        // URL to be converted to PDF
        string url = "https://apple.com";
        // Path for the output PDF file
        string outputPdfFile = @"C:\path\to\output\url-to-pdf.pdf";
        // Execute wkhtmltopdf command
        Process process = new Process();
        process.StartInfo.FileName = "wkhtmltopdf";
        process.StartInfo.Arguments = $"\"{url}\" \"{outputPdfFile}\"";
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.Start();
        process.WaitForExit();
        Console.WriteLine($"PDF saved to: {outputPdfFile}");
    }
}
using System;
using System.Diagnostics;

class Program
{
    static void Main(string[] args)
    {
        // URL to be converted to PDF
        string url = "https://apple.com";
        // Path for the output PDF file
        string outputPdfFile = @"C:\path\to\output\url-to-pdf.pdf";
        // Execute wkhtmltopdf command
        Process process = new Process();
        process.StartInfo.FileName = "wkhtmltopdf";
        process.StartInfo.Arguments = $"\"{url}\" \"{outputPdfFile}\"";
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.Start();
        process.WaitForExit();
        Console.WriteLine($"PDF saved to: {outputPdfFile}");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Output

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 18

Explanation:

  • In this example, wkhtmltopdf directly accepts URLs as input.
  • The URL is passed as an argument to wkhtmltopdf, and the output is saved as a PDF to the specified path.

PuppeteerSharp: HTML to PDF Conversion

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 19

PuppeteerSharp is a .NET wrapper for Google’s Puppeteer, providing control over headless Chrome/Chromium. It excels at rendering JavaScript-heavy, dynamic pages but requires downloading and managing a Chromium instance, which adds overhead. It’s open-source under Apache 2.0.

HTML String to PDF

Puppeteer is designed for rendering full pages, so converting an HTML string requires writing it to a file or rendering it directly in a browser.

Example:

using PuppeteerSharp;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
       // Download the browser if necessary
        await new BrowserFetcher().DownloadAsync();
        var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
        var page = await browser.NewPageAsync();
        string htmlContent = "<h1>Hello, World!</h1><p>This is a PDF generated from HTML string.</p>";
        await page.SetContentAsync(htmlContent);
        // Save the page as a PDF
        await page.PdfAsync("html-string-to-pdf.pdf");
        await browser.CloseAsync();
    }
}
using PuppeteerSharp;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
       // Download the browser if necessary
        await new BrowserFetcher().DownloadAsync();
        var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
        var page = await browser.NewPageAsync();
        string htmlContent = "<h1>Hello, World!</h1><p>This is a PDF generated from HTML string.</p>";
        await page.SetContentAsync(htmlContent);
        // Save the page as a PDF
        await page.PdfAsync("html-string-to-pdf.pdf");
        await browser.CloseAsync();
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Output

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 20

Explanation:

  • Puppeteer.LaunchAsync: Launches a new instance of Chromium in headless mode.
  • page.SetContentAsync: Loads the HTML string into the browser page.
  • page.PdfAsync: Converts the loaded HTML into a PDF and saves it to a file.

Local HTML File to PDF

To convert a local HTML file into a PDF using PuppeteerSharp, you can load the file into a headless browser and generate the PDF.

Example:

using PuppeteerSharp;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        // Download the browser if necessary
        await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
        var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
        var page = await browser.NewPageAsync();

        // Load the local HTML file
        await page.GoToAsync("file:///path/to/your/template.html");

        // Save the page as a PDF
        await page.PdfAsync("html-file-to-pdf.pdf");
        await browser.CloseAsync();
    }
}
using PuppeteerSharp;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        // Download the browser if necessary
        await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
        var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
        var page = await browser.NewPageAsync();

        // Load the local HTML file
        await page.GoToAsync("file:///path/to/your/template.html");

        // Save the page as a PDF
        await page.PdfAsync("html-file-to-pdf.pdf");
        await browser.CloseAsync();
    }
}
Imports PuppeteerSharp
Imports System
Imports System.Threading.Tasks

Friend Class Program
	Shared Async Function Main(ByVal args() As String) As Task
		' Download the browser if necessary
		Await (New BrowserFetcher()).DownloadAsync(BrowserFetcher.DefaultRevision)
		Dim browser = Await Puppeteer.LaunchAsync(New LaunchOptions With {.Headless = True})
		Dim page = Await browser.NewPageAsync()

		' Load the local HTML file
		Await page.GoToAsync("file:///path/to/your/template.html")

		' Save the page as a PDF
		Await page.PdfAsync("html-file-to-pdf.pdf")
		Await browser.CloseAsync()
	End Function
End Class
$vbLabelText   $csharpLabel

Output

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 21

Explanation:

  • page.GoToAsync: Loads the local HTML file (make sure to use the correct [file://]() path).
  • page.PdfAsync: Converts the content of the local HTML file into a PDF.

URL to PDF

Converting a URL to a PDF is one of the core features of PuppeteerSharp, as it can handle complex pages with JavaScript.

Example:

using PuppeteerSharp;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        // Download the browser if necessary
        await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
        var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
        var page = await browser.NewPageAsync();

        // Navigate to the URL
        await page.GoToAsync("https://example.com");

        // Save the page as a PDF
        await page.PdfAsync("url-to-pdf.pdf");
        await browser.CloseAsync();
    }
}
using PuppeteerSharp;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        // Download the browser if necessary
        await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
        var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
        var page = await browser.NewPageAsync();

        // Navigate to the URL
        await page.GoToAsync("https://example.com");

        // Save the page as a PDF
        await page.PdfAsync("url-to-pdf.pdf");
        await browser.CloseAsync();
    }
}
Imports PuppeteerSharp
Imports System
Imports System.Threading.Tasks

Friend Class Program
	Shared Async Function Main(ByVal args() As String) As Task
		' Download the browser if necessary
		Await (New BrowserFetcher()).DownloadAsync(BrowserFetcher.DefaultRevision)
		Dim browser = Await Puppeteer.LaunchAsync(New LaunchOptions With {.Headless = True})
		Dim page = Await browser.NewPageAsync()

		' Navigate to the URL
		Await page.GoToAsync("https://example.com")

		' Save the page as a PDF
		Await page.PdfAsync("url-to-pdf.pdf")
		Await browser.CloseAsync()
	End Function
End Class
$vbLabelText   $csharpLabel

Output

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 22

Explanation:

  • page.GoToAsync: Navigates to the specified URL.
  • page.PdfAsync: Converts the web page at the URL into a PDF and saves it.

Verdict / When to Use

PuppeteerSharp is ideal when you need pixel-perfect rendering of modern, JavaScript-heavy web applications. It’s more complex than IronPDF but excels in handling dynamic web content.

Why Choose IronPDF?

IronPDF stands out due to its ease of use, flexibility, and seamless integration with .NET applications. It is simple to implement, supports HTML, CSS, and JavaScript rendering, and doesn’t require additional setup or external dependencies. Beyond HTML to PDF conversion, IronPDF offers an extensive range of features for creating PDF documents from various file types, editing and adding to existing PDF documents, watermarking, PDF file security, and more! To see more of this library in action, be sure to check out the How-to Guides which demonstrate each of its features at work.

Conclusion

When it comes to converting HTML to PDF files in C#, there are several powerful tools available, each offering unique features and capabilities. IronPDF, Aspose, iText 9, wkhtmltopdf, and PuppeteerSharp all provide robust solutions for turning HTML content into professional-grade PDF documents. However, choosing the right tool for your project depends on factors like ease of integration, support for dynamic content, performance, and flexibility.

ToolHTML String to PDFHTML File to PDFURL to PDFNotes
logo of IronPDF
IronPDF
Simple with RenderHtmlAsPdf for HTML strings. Easy to use and integrates seamlessly into .NET applications.Uses RenderHtmlFileAsPdf, handles linked resources (CSS, JS) automatically.Uses RenderUrlAsPdf, supports JavaScript-heavy pages and dynamic content.Fully integrated into .NET, making it ideal for .NET developers. Supports HTML strings, files, and URLs.
logo of Aspose
Aspose
Requires more setup. Uses HtmlFragment in a Document object to convert HTML strings.Requires HtmlDocument and PdfSaveOptions for local HTML file conversion. Needs more configuration than IronPDF.Requires an extra setup using WebRequest to fetch content before converting with HtmlLoadOptions.Robust for various document manipulations, but setup can be more involved. Good for more complex PDF needs.
logo of iText
iText7
Uses HtmlConverter.ConvertToPdf to convert HTML strings to PDF.Uses HtmlConverter.ConvertToPdf to convert local HTML files to PDFs.Similar to local file handling, uses HtmlConverter.ConvertToPdf.Great for developers who need more control over PDF manipulation beyond HTML to PDF conversion.
logo of wkhtmltopdf
wkhtmltopdf
Converts HTML strings by writing them to a file first. Uses the command-line tool to generate PDFs.Directly converts local HTML files to PDFs by pointing to file paths.Directly converts URLs to PDFs by passing the URL to the command-line tool.Primarily a command-line tool, may require extra steps for integration in .NET. Best for simple conversions.
logo of PuppeteerSharp
PuppeteerSharp
Uses page.SetContentAsync to load the HTML string and then page.PdfAsync to generate a PDF.Loads a local HTML file via page.GoToAsync and then converts it to a PDF.Loads a URL and converts it to a PDF using page.GoToAsync and page.PdfAsync.Best suited for dynamic pages, especially JavaScript-heavy content. Requires downloading and launching Chromium.
  • IronPDF stands out for its simplicity, direct integration with .NET, and ability to handle complex HTML, including JavaScript-rendered pages. It’s perfect for developers looking for an easy-to-use solution with minimal setup.

  • Aspose offers extensive PDF manipulation features, but its HTML-to-PDF conversion capabilities require more configuration, especially for handling local files and external resources.

  • iText 9 provides a solid foundation for those looking to create PDF documents, though it may require additional coding to convert HTML to PDF, especially for dynamic content. It’s a great choice for projects where custom PDF manipulation is needed.

  • wkhtmltopdf is ideal for basic HTML-to-PDF conversion with a command-line interface, but it lacks the integration and flexibility of a full .NET library.

  • PuppeteerSharp, leveraging headless Chrome, is the go-to tool for rendering complex, dynamic web pages and converting them into PDFs, especially when dealing with JavaScript-heavy content.

For most .NET developers looking for an all-in-one, straightforward solution, IronPDF is worth trying today to experience its powerful features for yourself. From generating new PDF documents, to editing existing PDFs, explore the full range of IronPDF's features for yourself. Just install IronPDF, and use the free trial to try it for yourself. See how it can elevate your PDF workflows today.

Ultimately, the right tool depends on your specific requirements, but with the options discussed here, you're well-equipped to find the perfect solution for your project.

Please note: Aspose, iText, wkhtmltopdf, and PuppeteerSharp are registered trademarks of their respective owners. This site is not affiliated with, endorsed by, or sponsored by Aspose, iText, wkhtmltopdf, or Puppeteer. All product names, logos, and brands are the property of their respective owners. Comparisons are provided for informational purposes only and are based on publicly available information at the time of writing.