PRODUCT COMPARISONS

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

Published December 15, 2024
Share:

Introduction

In today's web-driven world, the ability to convert HTML content into PDF documents is a crucial feature for many applications. Whether it's for generating reports, invoices, or saving web pages for offline use, HTML to PDF conversion plays a pivotal role in streamlining workflows and enhancing user experiences. For .NET developers, choosing the right tool to handle this conversion can significantly impact the efficiency and quality of their applications.

In this article, we'll explore how to convert HTML to PDF in C# by covering the following topics:

  1. Why Compare HTML to PDF Tools? 2. IronPDF: HTML to PDF Conversion

  2. Aspose: HTML to PDF Conversion 4. iText7: HTML to PDF Conversion

  3. wkhtmltopdf: HTML to PDF Conversion 6. PuppeteerSharp: HTML to PDF Conversion

  4. Conclusion Why Choose IronPDF?

By the end, you'll understand why IronPDF stands out as a developer-friendly and efficient HTML to PDF converter.

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 features and 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.
  • Code Simplicity: The ease of writing and maintaining code using the library.
  • Rendering Accuracy: The ability to accurately render complex HTML, CSS, and JavaScript.
  • Performance at Scale: How well the library performs under heavy load and large-scale PDF generation.
  • Licensing and Cost-Effectiveness: The pricing models and licensing terms suitable for your project's budget.

By assessing these factors, you can choose a tool that not only fits your technical requirements but also aligns with your project's financial constraints.

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 for converting HTML to PDF. It supports HTML strings, local HTML files, and URLs, making it versatile for a wide range of use cases. Here’s how IronPDF handles each scenario:

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();
        PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>");
        PDF.SaveAs("output.pdf");
    }
}
using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>");
        PDF.SaveAs("output.pdf");
    }
}
Imports IronPdf
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()
		Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>")
		PDF.SaveAs("output.pdf")
	End Sub
End Class
VB   C#

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
VB   C#

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();
        PdfDocument pdf = renderer.RenderUrlAsPdf("https://ironpdf.com");
        pdf.SaveAs("url-to-pdf.pdf");
    }
}
using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        PdfDocument pdf = renderer.RenderUrlAsPdf("https://ironpdf.com");
        pdf.SaveAs("url-to-pdf.pdf");
    }
}
Imports IronPdf
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()
		Dim pdf As PdfDocument = renderer.RenderUrlAsPdf("https://ironpdf.com")
		pdf.SaveAs("url-to-pdf.pdf")
	End Sub
End Class
VB   C#

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.

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;
Document doc = new Document();
Page page = doc.getPages().add();
HtmlFragment htmlFragment = new HtmlFragment("<h1>HTML String</h1>");
page.getParagraphs().add(htmlFragment);
doc.save(dataDir + "HTMLStringUsingDOM.pdf");
using Aspose.Html;
Document doc = new Document();
Page page = doc.getPages().add();
HtmlFragment htmlFragment = new HtmlFragment("<h1>HTML String</h1>");
page.getParagraphs().add(htmlFragment);
doc.save(dataDir + "HTMLStringUsingDOM.pdf");
Imports Aspose.Html
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(dataDir & "HTMLStringUsingDOM.pdf")
VB   C#

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;
    using 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;
    using 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")
VB   C#

Explanation:

  • using 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;
using Aspose.Pdf;
string dataDir = "YOUR DOCUMENT DIRECTORY"; // Replace with your path
WebRequest request = WebRequest.Create("https://en.wikipedia.org/wiki/Main_Page");
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseFromServer));
HtmlLoadOptions options = new HtmlLoadOptions("https://en.wikipedia.org/wiki/");
Document pdfDocument = new Document(stream, options);
pdfDocument.Save(dataDir + "WebPageToPDF_out.pdf");
using System.IO;
using System;
using System.Net;
using Aspose.Pdf;
string dataDir = "YOUR DOCUMENT DIRECTORY"; // Replace with your path
WebRequest request = WebRequest.Create("https://en.wikipedia.org/wiki/Main_Page");
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseFromServer));
HtmlLoadOptions options = new HtmlLoadOptions("https://en.wikipedia.org/wiki/");
Document pdfDocument = new Document(stream, options);
pdfDocument.Save(dataDir + "WebPageToPDF_out.pdf");
Imports System.IO
Imports System
Imports System.Net
Imports Aspose.Pdf
Private dataDir As String = "YOUR DOCUMENT DIRECTORY" ' Replace with your path
Private request As WebRequest = WebRequest.Create("https://en.wikipedia.org/wiki/Main_Page")
request.Credentials = CredentialCache.DefaultCredentials
Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
Dim dataStream As Stream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
dataStream.Close()
response.Close()
Dim stream As New MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseFromServer))
Dim options As New HtmlLoadOptions("https://en.wikipedia.org/wiki/")
Dim pdfDocument As New Document(stream, options)
pdfDocument.Save(dataDir & "WebPageToPDF_out.pdf")
VB   C#

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.

iText7: HTML to PDF Conversion

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

iText7 is a comprehensive PDF library that also supports HTML-to-PDF conversion. Here’s how iText7 performs in different scenarios:

HTML String to PDF

iText7 makes use of its htmlConverter class to convert HTML string to PDF format.

Example:

public static String DEST = String.Format("{0}test-03.pdf", TARGET);
var html = "<h1>Hello World</h1>";
HtmlConverter.ConvertToPdf(html, new FileStream(dest, FileMode.Create));
public static String DEST = String.Format("{0}test-03.pdf", TARGET);
var html = "<h1>Hello World</h1>";
HtmlConverter.ConvertToPdf(html, new FileStream(dest, FileMode.Create));
Public Shared DEST As String = String.Format("{0}test-03.pdf", TARGET)
Private html = "<h1>Hello World</h1>"
HtmlConverter.ConvertToPdf(html, New FileStream(dest, FileMode.Create))
VB   C#

Local HTML File to PDF

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

Example:

using iText.Html2pdf;
class Program
{
    static void Main(string[] args)
    {
        HtmlConverter.ConvertToPdf("template.html", new FileStream("html-file-to-pdf.pdf", FileMode.Create));
    }
}
using iText.Html2pdf;
class Program
{
    static void Main(string[] args)
    {
        HtmlConverter.ConvertToPdf("template.html", new FileStream("html-file-to-pdf.pdf", FileMode.Create));
    }
}
Imports iText.Html2pdf
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		HtmlConverter.ConvertToPdf("template.html", New FileStream("html-file-to-pdf.pdf", FileMode.Create))
	End Sub
End Class
VB   C#

Explanation:

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

URL to PDF

iText7 also supports converting content from URLs.

Example:

using iText.Html2pdf;
class Program
{
    static void Main(string[] args)
    {
        HtmlConverter.ConvertToPdf("https://example.com", new FileStream("url-to-pdf.pdf", FileMode.Create));
    }
}
using iText.Html2pdf;
class Program
{
    static void Main(string[] args)
    {
        HtmlConverter.ConvertToPdf("https://example.com", new FileStream("url-to-pdf.pdf", FileMode.Create));
    }
}
Imports iText.Html2pdf
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		HtmlConverter.ConvertToPdf("https://example.com", New FileStream("url-to-pdf.pdf", FileMode.Create))
	End Sub
End Class
VB   C#

Explanation:

  • HtmlConverter: Manages the URL content and converts it into a PDF.

wkhtmltopdf: HTML to PDF Conversion

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

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
VB   C#

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\template.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\template.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}");
    }
}
Imports System
Imports System.Diagnostics
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Path to the local HTML file
		Dim htmlFilePath As String = "C:\path\to\your\template.html"
		' Path for the output PDF file
		Dim outputPdfFile As String = "C:\path\to\output\html-file-to-pdf.pdf"
		' Execute wkhtmltopdf command
		Dim process As 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}")
	End Sub
End Class
VB   C#

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://example.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://example.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}");
    }
}
Imports System
Imports System.Diagnostics
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' URL to be converted to PDF
		Dim url As String = "https://example.com"
		' Path for the output PDF file
		Dim outputPdfFile As String = "C:\path\to\output\url-to-pdf.pdf"
		' Execute wkhtmltopdf command
		Dim process As 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}")
	End Sub
End Class
VB   C#

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 9

PuppeteerSharp is a powerful tool for automating headless Chrome or Chromium, often used for web scraping or rendering complex web pages. Below are examples of how to use PuppeteerSharp for converting HTML to PDF.

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(BrowserFetcher.DefaultRevision);
        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(BrowserFetcher.DefaultRevision);
        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();
    }
}
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()
		Dim htmlContent As String = "<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()
	End Function
End Class
VB   C#

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
VB   C#

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
VB   C#

Explanation:

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

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 a 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, iText7, 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.

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

  • 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.
  • iText7 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 today to experience its powerful features for yourself.

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.

< PREVIOUS
C# PDF SDK Comparison (Free & Paid Tools)
NEXT >
APITemplate io and IronPDF Comparison for C# PDF Libraries

Ready to get started? Version: 2024.12 just released

Free NuGet Download Total downloads: 11,938,203 View Licenses >