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
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:
By the end, you'll understand why IronPDF stands out as a developer-friendly and efficient HTML to PDF converter.
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:
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 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:
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");
}
}
Explanation:
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.
RenderHtmlAsPdf: This method takes an HTML string as input and generates a PDF document.
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");
}
}
Input HTML File
Output
Explanation:
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");
}
}
Explanation:
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:
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");
Explanation:
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");
Explanation:
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");
Explanation:
iText7 is a comprehensive PDF library that also supports HTML-to-PDF conversion. Here’s how iText7 performs in different scenarios:
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));
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));
}
}
Explanation:
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));
}
}
Explanation:
wkhtmltopdf is a command-line tool that converts HTML files to PDF using Webkit rendering. Here’s how it works for different scenarios:
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}");
}
}
Explanation:
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}");
}
}
Explanation:
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}");
}
}
Explanation:
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.
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();
}
}
Explanation:
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();
}
}
Explanation:
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();
}
}
Explanation:
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.
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.
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.