HTML to PDF: A Quick Tutorial for C# .NET

How to Convert HTML to PDF in C# (Developer Guide)

Converting HTML to PDF in C# often seems simple until real-world requirements surface. Developers quickly encounter limitations that impact rendering accuracy, deployment, and scalability.

Beyond rendering, infrastructure compatibility becomes critical. Teams must ensure PDF generation works across modern .NET runtimes, cloud platforms, and containerized environments without performance trade-offs.

To address these gaps, modern Chrome-based solutions like IronPDF provide higher rendering fidelity, broader platform support, and production-ready deployment workflows—explored step-by-step in the rest of this guide.

TL;DR: Quickstart Guide to Convert HTML to PDF

You can easily convert HTML to PDF in C# using the IronPDF library, which provides the ChromePdfRenderer.RenderHtmlAsPdf method to create high-quality PDF files from HTML, CSS, and JavaScript.

  1. Install IronPDF with NuGet Package Manager

    PM > Install-Package IronPdf
  2. Copy and run this code snippet.

    IronPdf.ChromePdfRenderer
           .StaticRenderHtmlAsPdf("<p>Hello World</p>")
           .SaveAs("pixelperfect.pdf");
  3. Deploy to test on your live environment

    Start using IronPDF in your project today with a free trial

    arrow pointer

After you've purchased or signed up for a 30-day trial of IronPDF, find the license key sent to your email. Add your license key at the start of your application.

IronPdf.License.LicenseKey = "KEY";
IronPdf.License.LicenseKey = "KEY";
$vbLabelText   $csharpLabel

Why NET Developers Need an HTML to PDF Converter for C#

IronPDF leverages an embedded Google Chromium rendering engine to ensure high-fidelity conversions, accurately preserving the layout and styling of your web content.

Robust Chrome Rendering Engine: Chrome's Blink engine for accurate HTML to PDF conversion, now enhanced with fixes for memory, forms, and rendering accuracy (v2025.9.4)

Pixel-Perfect Accuracy: Generated PDFs match the web precisely, not a printer-friendly version. Recent fixes cover custom header/footer clipping, grayscale text preservation, and special characters/emojis in metadata (as of v2025.9.4)

Full Modern Web Support: Complete CSS3, HTML5, JavaScript support for all HTML elements. Recent enhancements covert form field handling for long textareas and checkboxes.

5-20x Performance Boost: Significantly faster than browser automation or web drivers, now with memory leak fixes and reduced file sizes for repeated elements like stamps/headers in batch operations.

PDF/UA Compliance: Accessible PDF generation that meets Section 508 standards, enhanced for cross-platform (e.g., Linux) form rendering.

No External Dependencies: No executables to install on servers

✅ Designed for C#, F#, & VB.NET running on .NET 10, 9, 8, 7, 6, Core, Standard, or Framework

IronPDF simplifies the process for .NET developers, offering a straightforward and efficient solution for generating professional-looking PDF documents from your web application's HTML. From invoices and reports to certificates and archives, developers can work with their familiar web stack while IronPDF handles the complex in just a few lines of code.

RELATED: IronPDF Changelog: Updates, milestones, roadmap

What You'll Learn

  1. How to Convert HTML to PDF C#

  2. How to Configure HTML to PDF Settings

  3. How to Use Advanced PDF Generation & Security Features

  4. How to Deploy HTML to PDF on Cloud Platforms

  5. Compare IronPDF with Other .NET PDF Libraries

  6. Troubleshooting & Technical Support

1. How to Convert HTML to PDF C#

Whether you're working with HTML strings, URLs, or HTML files, IronPDF provides flexible options to generate high-quality PDF documents that meet your specific requirements.

In this tutorial, we will walk you through the most common scenarios, including HTML string to PDF, URL to PDF, and HTML file to PDF. Additionally, IronPDF also provides a variety of operations for manipulating PDF documents:

Versatile PDF Conversion Dynamic Web Page to PDF Conversion

How to Convert HTML String to PDF

The most fundamental operation is HTML string to PDF. This method is perfect for dynamically generated HTML content. The RenderHtmlAsPdf method fully supports HTML5, CSS3, JavaScript, and images when you convert HTML to PDF directly.

using IronPdf;

// Create the Chrome renderer
var renderer = new ChromePdfRenderer();

// Convert HTML string to PDF
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>");

// Save the PDF
pdf.SaveAs("output.pdf");
using IronPdf;

// Create the Chrome renderer
var renderer = new ChromePdfRenderer();

// Convert HTML string to PDF
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>");

// Save the PDF
pdf.SaveAs("output.pdf");
$vbLabelText   $csharpLabel

Tips(Updated for v2025.9.4) Recent updates fix issues with special characters/emojis in HTML metadata and ensure better handling of html form fields, including Chinese characters on Linux. Test dynamic content with EnableJavaScript = true for optimal results.

When your HTML string references local assets like images or stylesheets, use the BaseUrlPath parameter to properly convert HTML content with all resources:

using IronPdf;

var renderer = new ChromePdfRenderer();

// Convert HTML content with local image and CSS references
string html = @"
    <link rel='stylesheet' href='styles.css'>
    <img src='logo.png' alt='Company Logo'>
    <h1>Company Report</h1>
    <p>Annual report content...</p>";

// Set base path for resolving relative URLs in HTML to PDF conversion
var pdf = renderer.RenderHtmlAsPdf(html, @"C:\MyProject\Assets\");
pdf.SaveAs("report.pdf");
using IronPdf;

var renderer = new ChromePdfRenderer();

// Convert HTML content with local image and CSS references
string html = @"
    <link rel='stylesheet' href='styles.css'>
    <img src='logo.png' alt='Company Logo'>
    <h1>Company Report</h1>
    <p>Annual report content...</p>";

// Set base path for resolving relative URLs in HTML to PDF conversion
var pdf = renderer.RenderHtmlAsPdf(html, @"C:\MyProject\Assets\");
pdf.SaveAs("report.pdf");
$vbLabelText   $csharpLabel

TipsBaseUrlPath tells IronPDF where to find your CSS, JavaScript, and image files. All relative paths in your HTML string will be resolved from this directory.

RELATED HOW-TO ARTICLE: How to Convert HTML String to PDF in C#

How to Export Existing URL to PDF

Rendering entire web pages to PDFs with C# enables teams to separate PDF design and back-end rendering work. This approach lets you convert any specified URL directly to PDF format.

Print vs Screen CSS

You can configure IronPDF to render using either CSS media type.

using IronPdf;
using IronPdf.Rendering;

// Initialize HTML to PDF converter
var renderer = new ChromePdfRenderer();

// Configure CSS media type for rendering specified URLs
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;

// Screen media type shows the entire web page as displayed on screen
using IronPdf;
using IronPdf.Rendering;

// Initialize HTML to PDF converter
var renderer = new ChromePdfRenderer();

// Configure CSS media type for rendering specified URLs
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;

// Screen media type shows the entire web page as displayed on screen
$vbLabelText   $csharpLabel

JavaScript Support

IronPDF fully supports JavaScript, jQuery, and even AJAX when you convert HTML to PDF. For dynamic HTML content, you can configure IronPDF to wait for JavaScript completion before rendering web pages into PDF. This is perfect for single-page applications and dynamic websites.

using IronPdf;

// Configure JavaScript rendering for dynamic HTML content to PDF
var renderer = new ChromePdfRenderer();

// Enable JavaScript execution during PDF generation
renderer.RenderingOptions.EnableJavaScript = true;

// WaitFor.RenderDelay pauses before capturing the HTML
renderer.RenderingOptions.WaitFor.RenderDelay = 500; // milliseconds
using IronPdf;

// Configure JavaScript rendering for dynamic HTML content to PDF
var renderer = new ChromePdfRenderer();

// Enable JavaScript execution during PDF generation
renderer.RenderingOptions.EnableJavaScript = true;

// WaitFor.RenderDelay pauses before capturing the HTML
renderer.RenderingOptions.WaitFor.RenderDelay = 500; // milliseconds
$vbLabelText   $csharpLabel

JavaScript execution can also be shown when rendering an advanced d3.js chord chart from a web page to PDF format:

using IronPdf;

// Create renderer for JavaScript-heavy HTML
var renderer = new ChromePdfRenderer();

// Convert d3.js visualization web page to PDF
var pdf = renderer.RenderUrlAsPdf("https://bl.ocks.org/mbostock/4062006");

// Save the interactive chart as static PDF
pdf.SaveAs("chart.pdf");
using IronPdf;

// Create renderer for JavaScript-heavy HTML
var renderer = new ChromePdfRenderer();

// Convert d3.js visualization web page to PDF
var pdf = renderer.RenderUrlAsPdf("https://bl.ocks.org/mbostock/4062006");

// Save the interactive chart as static PDF
pdf.SaveAs("chart.pdf");
$vbLabelText   $csharpLabel

Responsive CSS

As responsive web pages are designed to be viewed in a browser, and IronPDF does not open a real browser window in your server's OS, responsive HTML elements may render at their smallest size. PdfCssMediaType.Print is recommended to navigate this issue when rendering entire web pages.

// Configure for optimal responsive design handling in HTML to PDF

renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;
// Configure for optimal responsive design handling in HTML to PDF

renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;
$vbLabelText   $csharpLabel

RELATED HOW-TO ARTICLE: How to Render URL to PDF

How to Convert HTML File to PDF

Converting local HTML files to PDF preserves all relative assets including CSS, images, and JavaScript, as if opened using the file:// protocol. This HTML to PDF method is best for converting templates or pre-designed HTML pages to PDF documents.

using IronPdf;

// Initialize ChromePdfRenderer for HTML file conversion
var renderer = new ChromePdfRenderer();

// Convert HTML file to PDF documents
// Preserves all relative paths and linked resources in HTML
var pdf = renderer.RenderHtmlFileAsPdf("Assets/TestInvoice1.html");

// Save the HTML file as PDF 
pdf.SaveAs("Invoice.pdf");

// All CSS, JavaScript, and images load correctly in the generated PDF
using IronPdf;

// Initialize ChromePdfRenderer for HTML file conversion
var renderer = new ChromePdfRenderer();

// Convert HTML file to PDF documents
// Preserves all relative paths and linked resources in HTML
var pdf = renderer.RenderHtmlFileAsPdf("Assets/TestInvoice1.html");

// Save the HTML file as PDF 
pdf.SaveAs("Invoice.pdf");

// All CSS, JavaScript, and images load correctly in the generated PDF
$vbLabelText   $csharpLabel

TipsKeep your HTML files in a separate folder with their assets (CSS, images) to edit and test in a browser before converting HTML file to PDF. This ensures your HTML renders perfectly for high quality PDF documents.

RELATED HOW-TO Article: Render HTML File to PDF

How to Convert Razor Pages to PDF

If your ASP.NET Core project already uses Razor Pages, you can convert them directly to PDF without rebuilding your HTML. IronPDF's Razor extension adds the RenderRazorToPdf method, which takes your .cshtml page — complete with its model and layout — and renders it as a PDF document in a single call.

PM > Install-Package IronPdf.Extensions.Razor
PM > Install-Package IronPdf.Extensions.Razor
SHELL
using IronPdf;

var renderer = new ChromePdfRenderer();

// Render a Razor Page directly to PDF
PdfDocument pdf = renderer.RenderRazorToPdf(this);

Response.Headers.Add("Content-Disposition", "inline");
return new FileContentResult(pdf.BinaryData, "application/pdf");
using IronPdf;

var renderer = new ChromePdfRenderer();

// Render a Razor Page directly to PDF
PdfDocument pdf = renderer.RenderRazorToPdf(this);

Response.Headers.Add("Content-Disposition", "inline");
return new FileContentResult(pdf.BinaryData, "application/pdf");
$vbLabelText   $csharpLabel

Please noteRenderRazorToPdf requires an ASP.NET Core Web App project. It will not work in console applications or class libraries — the Razor view engine must be available in the hosting pipeline.

RELATED HOW-TO Article: How to Convert CSHTML to PDF in Razor Pages

How to Convert MVC Views to PDF

Teams using the MVC pattern can generate PDFs straight from their existing Views and controllers. Install the MVC Core extension package, then call RenderRazorViewToPdf with your view path and model — IronPDF handles the Razor rendering pipeline and outputs a finished PDF.

This is especially useful for reports, invoices, and any page where the HTML is already designed and tested in the browser. The generated PDF preserves the full View output, including layout pages and partial views.

PM > Install-Package IronPdf.Extensions.Mvc.Core
PM > Install-Package IronPdf.Extensions.Mvc.Core
SHELL

First, register the IRazorViewRenderer service in your Program.cs so your controllers can inject it:

using IronPdf.Extensions.Mvc.Core;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();

// Register the Razor view renderer for IronPDF
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddSingleton<IRazorViewRenderer, RazorViewRenderer>();
using IronPdf.Extensions.Mvc.Core;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();

// Register the Razor view renderer for IronPDF
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddSingleton<IRazorViewRenderer, RazorViewRenderer>();
$vbLabelText   $csharpLabel

Then in your controller action, inject the renderer and convert any View to PDF:

using IronPdf;
using IronPdf.Extensions.Mvc.Core;

var renderer = new ChromePdfRenderer();

// Render an MVC View with model data to PDF
PdfDocument pdf = renderer.RenderRazorViewToPdf(
    _viewRenderService, "Views/Home/Report.cshtml", reportModel);

Response.Headers.Add("Content-Disposition", "inline");
return new FileContentResult(pdf.BinaryData, "application/pdf");
using IronPdf;
using IronPdf.Extensions.Mvc.Core;

var renderer = new ChromePdfRenderer();

// Render an MVC View with model data to PDF
PdfDocument pdf = renderer.RenderRazorViewToPdf(
    _viewRenderService, "Views/Home/Report.cshtml", reportModel);

Response.Headers.Add("Content-Disposition", "inline");
return new FileContentResult(pdf.BinaryData, "application/pdf");
$vbLabelText   $csharpLabel

RELATED HOW-TO Article: How to Convert Views to PDF in ASP.NET Core MVC

2. How to Configure HTML to PDF Settings

In terms of manipulating PDF documents, IronPDF provides extensive customizations through the ChromePdfRenderer.RenderingOptions property for rendered PDFs.

Settings Description Example
PaperSize Set page dimensions for existing PDFs (A4, Letter, Legal, etc.) `PdfPaperSize.A4`
PaperOrientation Set Portrait or Landscape for existing PDFs `PdfPaperOrientation.Landscape`
MarginTop/Bottom/Left/Right Set page margins in millimeters (default: 25mm)
CssMediaType Screen or Print CSS for HTML to PDF `PdfCssMediaType.Print`
PrintHtmlBackgrounds Include background colors/images (default: true) true
EnableJavaScript Execute JavaScript before rendering HTML content true
WaitFor.RenderDelay Wait time for dynamic HTML content (ms) 500

See this code snippet for a complete configuration example for manipulating PDF documents:

using IronPdf;
using IronPdf.Rendering;

var renderer = new ChromePdfRenderer();

// Apply print-specific CSS rules
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;

// Set custom margins in millimeters
renderer.RenderingOptions.MarginTop = 50;
renderer.RenderingOptions.MarginBottom = 50;

// Enable background colors and images
renderer.RenderingOptions.PrintHtmlBackgrounds = true;

// Set paper size and orientation
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Landscape;

// Generate PDFs with all settings applied to HTML content
var htmlContent = "<div style='background-color: #f0f0f0; padding: 20px;'><h1>Styled Content</h1></div>";
var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
pdfDocument.SaveAs("styled-output.pdf");
using IronPdf;
using IronPdf.Rendering;

var renderer = new ChromePdfRenderer();

// Apply print-specific CSS rules
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;

// Set custom margins in millimeters
renderer.RenderingOptions.MarginTop = 50;
renderer.RenderingOptions.MarginBottom = 50;

// Enable background colors and images
renderer.RenderingOptions.PrintHtmlBackgrounds = true;

// Set paper size and orientation
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Landscape;

// Generate PDFs with all settings applied to HTML content
var htmlContent = "<div style='background-color: #f0f0f0; padding: 20px;'><h1>Styled Content</h1></div>";
var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
pdfDocument.SaveAs("styled-output.pdf");
$vbLabelText   $csharpLabel

TipsUse PdfCssMediaType for cleaner, print-optimized layouts in your rendered PDF file format. Use Screen to match exactly what users see in their browser.

RELATED HOW-TO ARTICLES:

Tailor PDF Conversion Refine PDF Layout

How to Set Custom HTTP Headers, Cookies, and Login Credentials

When rendering URLs that require authentication or specific request metadata, IronPDF allows you to include login credentials, session cookies, and HTTP headers with the request. This enables rendering of intranet dashboards, restricted reports, or API-generated pages directly to PDF without needing to retrieve the HTML separately.

For basic or NTLM authentication, set a LoginCredentials object on the renderer. For token-based or session-based access, pass cookies and headers through RenderingOptions before calling RenderUrlAsPdf.

using IronPdf;

var renderer = new ChromePdfRenderer();

// Network authentication (Basic, Digest, NTLM)
renderer.LoginCredentials = new ChromeHttpLoginCredentials
{
    NetworkUsername = "user@domain.com",
    NetworkPassword = "securePassword"
};

// Session cookies for authenticated pages
renderer.RenderingOptions.CustomCookies["sessionId"] = "abc123";

// Custom HTTP headers (e.g., Bearer tokens, API keys)
renderer.RenderingOptions.CustomHttpRequestHeaders["Authorization"] = "Bearer eyJhbGciOi...";

var pdf = renderer.RenderUrlAsPdf("https://intranet.company.com/quarterly-report");
pdf.SaveAs("quarterly-report.pdf");
using IronPdf;

var renderer = new ChromePdfRenderer();

// Network authentication (Basic, Digest, NTLM)
renderer.LoginCredentials = new ChromeHttpLoginCredentials
{
    NetworkUsername = "user@domain.com",
    NetworkPassword = "securePassword"
};

// Session cookies for authenticated pages
renderer.RenderingOptions.CustomCookies["sessionId"] = "abc123";

// Custom HTTP headers (e.g., Bearer tokens, API keys)
renderer.RenderingOptions.CustomHttpRequestHeaders["Authorization"] = "Bearer eyJhbGciOi...";

var pdf = renderer.RenderUrlAsPdf("https://intranet.company.com/quarterly-report");
pdf.SaveAs("quarterly-report.pdf");
$vbLabelText   $csharpLabel

RELATED HOW-TO ARTICLES: Render PDFs Behind Login Authentication | Custom HTTP Request Headers

How to Configure Proxy for PDF Rendering

When rendering HTML that loads external resources behind a corporate proxy, pass the proxy address as the third parameter on RenderHtmlAsPdf(). This is a method parameter, not a property on ChromePdfRenderOptions — so it's set per render call, not on the renderer instance.

For authenticated proxies, embed credentials directly in the URL using http://user:pass@host:port format. URL-encode special characters in passwords with Uri.EscapeDataString().

using IronPdf;

var renderer = new ChromePdfRenderer();

// Proxy is the third parameter — not a render option
PdfDocument pdf = renderer.RenderHtmlAsPdf(
    "<h1>Report</h1><link rel='stylesheet' href='https://cdn.example.com/styles.css'>",
    baseUrlOrPath: null,
    proxy: "http://proxy.corp.local:8080"
);
pdf.SaveAs("proxied-report.pdf");
using IronPdf;

var renderer = new ChromePdfRenderer();

// Proxy is the third parameter — not a render option
PdfDocument pdf = renderer.RenderHtmlAsPdf(
    "<h1>Report</h1><link rel='stylesheet' href='https://cdn.example.com/styles.css'>",
    baseUrlOrPath: null,
    proxy: "http://proxy.corp.local:8080"
);
pdf.SaveAs("proxied-report.pdf");
$vbLabelText   $csharpLabel

Note that RenderUrlAsPdf() does not accept a proxy parameter. To render a live URL behind a proxy, fetch the HTML first with HttpClient configured with a WebProxy, then pass it to RenderHtmlAsPdf() with the proxy parameter for asset loading.

RELATED HOW-TO Article: How to Configure Proxy Servers for PDF Rendering

3. How to Use Advanced PDF Generation & Security Features

Unlock enterprise-level capabilities for HTML to PDF conversion with advanced templating, async operations, and security features. These PDF manipulation methods enable you to create PDF documents at scale, protect sensitive PDF files, and ensure document authenticity when you convert HTML to professional PDF format.

How to Generate HTML Template for Batch PDF Creation

Basic Batch PDF Creation

Batch PDF creation is essential for generating multiple personalized PDF documents efficiently. For basic scenarios, the String.Format method in C# works best for simple PDF manipulation.

// Simple HTML templating with String.Format
string htmlTemplate = String.Format("<h1>Hello {0}!</h1>", "World");

// Results in HTML content: <h1>Hello World!</h1>
// Simple HTML templating with String.Format
string htmlTemplate = String.Format("<h1>Hello {0}!</h1>", "World");

// Results in HTML content: <h1>Hello World!</h1>
$vbLabelText   $csharpLabel

For longer templates when you need to generate PDF documents, use placeholder replacement in your HTML content: using IronPdf;

// Define reusable HTML template for PDF files
var htmlTemplate = "<p>Dear [[NAME]],</p><p>Thank you for your order.</p>";

// Customer names for batch PDF conversion processing
var names = new[] { "John", "James", "Jenny" };

// Create personalized PDF documents for each customer
var renderer = new ChromePdfRenderer();

foreach (var name in names)
{
    // Replace placeholder with actual data in HTML string
    var htmlInstance = htmlTemplate.Replace("[[NAME]]", name);

    // Generate personalized PDF document from HTML content
    var pdf = renderer.RenderHtmlAsPdf(htmlInstance);

    // Save with customer-specific filename as PDF files
    pdf.SaveAs($"{name}-invoice.pdf");
}
// Define reusable HTML template for PDF files
var htmlTemplate = "<p>Dear [[NAME]],</p><p>Thank you for your order.</p>";

// Customer names for batch PDF conversion processing
var names = new[] { "John", "James", "Jenny" };

// Create personalized PDF documents for each customer
var renderer = new ChromePdfRenderer();

foreach (var name in names)
{
    // Replace placeholder with actual data in HTML string
    var htmlInstance = htmlTemplate.Replace("[[NAME]]", name);

    // Generate personalized PDF document from HTML content
    var pdf = renderer.RenderHtmlAsPdf(htmlInstance);

    // Save with customer-specific filename as PDF files
    pdf.SaveAs($"{name}-invoice.pdf");
}
$vbLabelText   $csharpLabel

HTML to PDF Templating with Handlebars.NET

For complex templates with loops and conditionals when you convert HTML to PDF, use advanced templating with Handlebars.NET to generate PDF documents with dynamic HTML content.

# First, install Handlebars.NET for HTML to PDF templating
PM > Install-Package Handlebars.NET
# First, install Handlebars.NET for HTML to PDF templating
PM > Install-Package Handlebars.NET
SHELL
using HandlebarsDotNet;
using IronPdf;

// Define Handlebars template with placeholders for HTML content
var source = 
    @"<div class=""entry"">
        <h1>{{title}}</h1>
        <div class=""body"">
            {{body}}
        </div>
    </div>";

// Compile template for reuse in PDF conversion
var template = Handlebars.Compile(source);

// Create data object (can be database records) for HTML to PDF directly
var data = new { 
    title = "Monthly Report", 
    body = "Sales increased by 15% this month." 
};

// Merge template with data to create HTML content
var htmlResult = template(data);

// Convert templated HTML to PDF using the PDF converter
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(htmlResult);

pdf.SaveAs("monthly-report.pdf");
using HandlebarsDotNet;
using IronPdf;

// Define Handlebars template with placeholders for HTML content
var source = 
    @"<div class=""entry"">
        <h1>{{title}}</h1>
        <div class=""body"">
            {{body}}
        </div>
    </div>";

// Compile template for reuse in PDF conversion
var template = Handlebars.Compile(source);

// Create data object (can be database records) for HTML to PDF directly
var data = new { 
    title = "Monthly Report", 
    body = "Sales increased by 15% this month." 
};

// Merge template with data to create HTML content
var htmlResult = template(data);

// Convert templated HTML to PDF using the PDF converter
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(htmlResult);

pdf.SaveAs("monthly-report.pdf");
$vbLabelText   $csharpLabel

RELATED HOW-TO ARTICLE: Learn more about Handlebars.NET on GitHub

Control PDF Page Breaks:

Managing pagination in generated PDF documents ensures professional, readable layouts when you convert HTML snippets. Use CSS to control where pages break in your PDF files.
<!DOCTYPE html>
<html>
  <head>
    <style type="text/css" media="print">
      .page {
        page-break-after: always;
        page-break-inside: avoid;
      }
    </style>
  </head>
  <body>
    <div class="page">
      <h1>Page 1 Content</h1>
    </div>
    <div class="page">
      <h1>Page 2 Content</h1>
    </div>
    <div class="page">
      <h1>Page 3 Content</h1>
    </div>
  </body>
</html>
<!DOCTYPE html>
<html>
  <head>
    <style type="text/css" media="print">
      .page {
        page-break-after: always;
        page-break-inside: avoid;
      }
    </style>
  </head>
  <body>
    <div class="page">
      <h1>Page 1 Content</h1>
    </div>
    <div class="page">
      <h1>Page 2 Content</h1>
    </div>
    <div class="page">
      <h1>Page 3 Content</h1>
    </div>
  </body>
</html>
HTML

How to Generate PDF Using Async Method

IronPDF delivers enterprise-grade performance with full async and multithreading support for your HTML to PDF conversion requirements when you need to generate PDF files at scale.

using IronPdf;
using System.Threading.Tasks;

// Async method for non-blocking PDF generation from HTML content
public async Task<byte[]> GeneratePdfAsync(string html)
{
    var renderer = new ChromePdfRenderer();

    // Async HTML to PDF conversion preserves thread pool
    var pdf = await renderer.RenderHtmlAsPdfAsync(html);

    // Return PDF files as byte array for web responses
    return pdf.BinaryData;
}

// Concurrent batch PDF generation for multiple HTML strings
public async Task GenerateMultiplePdfsAsync(List<string> htmlTemplates)
{
    var renderer = new ChromePdfRenderer();

    // Create parallel conversion tasks to generate PDF documents
    var tasks = htmlTemplates.Select(html => 
        renderer.RenderHtmlAsPdfAsync(html)
    );

    // Await all PDF conversions simultaneously
    var pdfs = await Task.WhenAll(tasks);

    // Save generated PDF files from HTML content
    for (int i = 0; i < pdfs.Length; i++)
    {
        pdfs[i].SaveAs($"document-{i}.pdf");
    }
}
using IronPdf;
using System.Threading.Tasks;

// Async method for non-blocking PDF generation from HTML content
public async Task<byte[]> GeneratePdfAsync(string html)
{
    var renderer = new ChromePdfRenderer();

    // Async HTML to PDF conversion preserves thread pool
    var pdf = await renderer.RenderHtmlAsPdfAsync(html);

    // Return PDF files as byte array for web responses
    return pdf.BinaryData;
}

// Concurrent batch PDF generation for multiple HTML strings
public async Task GenerateMultiplePdfsAsync(List<string> htmlTemplates)
{
    var renderer = new ChromePdfRenderer();

    // Create parallel conversion tasks to generate PDF documents
    var tasks = htmlTemplates.Select(html => 
        renderer.RenderHtmlAsPdfAsync(html)
    );

    // Await all PDF conversions simultaneously
    var pdfs = await Task.WhenAll(tasks);

    // Save generated PDF files from HTML content
    for (int i = 0; i < pdfs.Length; i++)
    {
        pdfs[i].SaveAs($"document-{i}.pdf");
    }
}
$vbLabelText   $csharpLabel

TipsPerformance optimization tips for HTML to PDF conversion

  • Use 64-bit systems for optimal PDF generation performance.
  • Ensure adequate server resources when you generate PDF documents (avoid underpowered free tiers)
  • Allow sufficient RenderDelay for complex JavaScript in HTML content.
  • Reuse ChromePdfRenderer instances when possible.
  • Leverage v2025.9.4 memory fixes for batch/async ops to reduce resource usage; test for reduced file sizes with repeated custom headers/footers.

RELATED HOW-TO Article: How to Generate PDFs with Async and Multithreading

How to Add Advanced Security Features

How to Add Password Protect for PDF Files in .NET

Secure sensitive generated PDF documents with passwords and permissions when you convert HTML content to protected PDF format.

using IronPdf;
var renderer = new ChromePdfRenderer();

// Convert HTML to PDF with security
var pdf = renderer.RenderHtmlAsPdf("<h1>Confidential Report</h1>");

// Configure security settings for PDF files
pdf.SecuritySettings.UserPassword = "user123";     // Password to open PDF documents
pdf.SecuritySettings.OwnerPassword = "owner456";   // Password to modify PDF files

// Set granular permissions for PDF format
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserAnnotations = false;
pdf.SecuritySettings.AllowUserPrinting = PrintPermissions.LowQualityPrint;

// Apply strong encryption to PDF documents
pdf.SecuritySettings.EncryptionAlgorithm = PdfEncryptionAlgorithm.AES256;
pdf.SaveAs("secure-document.pdf");
using IronPdf;
var renderer = new ChromePdfRenderer();

// Convert HTML to PDF with security
var pdf = renderer.RenderHtmlAsPdf("<h1>Confidential Report</h1>");

// Configure security settings for PDF files
pdf.SecuritySettings.UserPassword = "user123";     // Password to open PDF documents
pdf.SecuritySettings.OwnerPassword = "owner456";   // Password to modify PDF files

// Set granular permissions for PDF format
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserAnnotations = false;
pdf.SecuritySettings.AllowUserPrinting = PrintPermissions.LowQualityPrint;

// Apply strong encryption to PDF documents
pdf.SecuritySettings.EncryptionAlgorithm = PdfEncryptionAlgorithm.AES256;
pdf.SaveAs("secure-document.pdf");
$vbLabelText   $csharpLabel

How to Add Digital Signatures to PDF Files

Add cryptographic signatures to ensure PDF document authenticity when you generate PDF files from HTML content.

using IronPdf;
using IronPdf.Signing;

var renderer = new ChromePdfRenderer();

// Generate PDF from HTML page
var pdf = renderer.RenderHtmlAsPdf("<h1>Contract Agreement</h1>");

// Create digital signature with certificate for PDF files
var signature = new PdfSignature("certificate.pfx", "password")
{
    SigningContact = "legal@company.com",
    SigningLocation = "New York, NY",
    SigningReason = "Contract Approval",
    SignerName = "Authorized Signer"  // New property in v2025.8.8 for enhanced signature details
};

// Apply signature to PDF documents
pdf.Sign(signature);
pdf.SaveAs("signed-contract.pdf");
using IronPdf;
using IronPdf.Signing;

var renderer = new ChromePdfRenderer();

// Generate PDF from HTML page
var pdf = renderer.RenderHtmlAsPdf("<h1>Contract Agreement</h1>");

// Create digital signature with certificate for PDF files
var signature = new PdfSignature("certificate.pfx", "password")
{
    SigningContact = "legal@company.com",
    SigningLocation = "New York, NY",
    SigningReason = "Contract Approval",
    SignerName = "Authorized Signer"  // New property in v2025.8.8 for enhanced signature details
};

// Apply signature to PDF documents
pdf.Sign(signature);
pdf.SaveAs("signed-contract.pdf");
$vbLabelText   $csharpLabel

RELATED HOW-TO Article: Digitally Signing PDF Documents with C#

How to Convert HTML Forms to Fillable PDFs

To convert standard HTML form elements into interactive, fillable PDF form fields, enable the CreatePdfFormsFromHtml rendering option. This preserves text inputs, checkboxes, radio buttons, and dropdown menus as editable fields in the generated PDF document.

using IronPdf;

var renderer = new ChromePdfRenderer();

// Enable HTML form to PDF form conversion
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;

string htmlForm = @"
    <h2>Employee Onboarding Form</h2>
    <form>
        <label>Full Name:</label>
        <input type='text' name='fullName' value='' /><br/>
        <label>Department:</label>
        <select name='department'>
            <option value='engineering'>Engineering</option>
            <option value='marketing'>Marketing</option>
            <option value='sales'>Sales</option>
        </select><br/>
        <label>Agree to Terms:</label>
        <input type='checkbox' name='agreeTerms' />
    </form>";

var pdf = renderer.RenderHtmlAsPdf(htmlForm);
pdf.SaveAs("onboarding-form.pdf");
using IronPdf;

var renderer = new ChromePdfRenderer();

// Enable HTML form to PDF form conversion
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;

string htmlForm = @"
    <h2>Employee Onboarding Form</h2>
    <form>
        <label>Full Name:</label>
        <input type='text' name='fullName' value='' /><br/>
        <label>Department:</label>
        <select name='department'>
            <option value='engineering'>Engineering</option>
            <option value='marketing'>Marketing</option>
            <option value='sales'>Sales</option>
        </select><br/>
        <label>Agree to Terms:</label>
        <input type='checkbox' name='agreeTerms' />
    </form>";

var pdf = renderer.RenderHtmlAsPdf(htmlForm);
pdf.SaveAs("onboarding-form.pdf");
$vbLabelText   $csharpLabel

WarningEach form field in your HTML must have a unique name attribute. Duplicate names will cause fields to share the same value in the generated PDF, leading to unexpected behavior when users fill out the form.

RELATED HOW-TO Article: How to Create Fillable PDF Forms in C#

How to Convert Specific HTML Elements to PDF

To render a specific section of a page rather than the full document, isolate the target element before rendering. The most direct approach uses the Javascript rendering option to replace the document body with the target element's content, combined with WaitFor.HtmlQuerySelector() to ensure the element exists before extraction. The snippet below preserves document.head so stylesheets and fonts carry over — without that step, CSS rules relying on ancestor selectors would be lost in the extracted PDF.

For server-side scenarios where you have access to the raw HTML, extract the target fragment with a parser like AngleSharp and pass it to RenderHtmlAsPdf() — no JavaScript execution needed.

using IronPdf;

var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.EnableJavaScript = true;

// Replace the body with only the target element
renderer.RenderingOptions.Javascript = @"
    var el = document.querySelector('#invoice-summary');
    if (el) {
        var head = document.head.innerHTML;
        document.body.innerHTML = el.outerHTML;
        document.head.innerHTML = head;
    }
";

// Wait for the target element before JS executes
renderer.RenderingOptions.WaitFor.HtmlQuerySelector("#invoice-summary", 10000);

var pdf = renderer.RenderHtmlAsPdf(fullPageHtml);
pdf.SaveAs("invoice-summary.pdf");
using IronPdf;

var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.EnableJavaScript = true;

// Replace the body with only the target element
renderer.RenderingOptions.Javascript = @"
    var el = document.querySelector('#invoice-summary');
    if (el) {
        var head = document.head.innerHTML;
        document.body.innerHTML = el.outerHTML;
        document.head.innerHTML = head;
    }
";

// Wait for the target element before JS executes
renderer.RenderingOptions.WaitFor.HtmlQuerySelector("#invoice-summary", 10000);

var pdf = renderer.RenderHtmlAsPdf(fullPageHtml);
pdf.SaveAs("invoice-summary.pdf");
$vbLabelText   $csharpLabel

RELATED HOW-TO Article: How to Convert HTML Elements and Partial Pages to PDF

How to Render Authenticated Pages to PDF

There are three mechanisms for rendering pages that sit behind authentication: network login credentials, custom cookies, and HTTP request headers. These cover the most common authentication scenarios when converting protected web content to PDF.

Login Credentials

Use ChromeHttpLoginCredentials for basic, digest, or NTLM authentication when converting protected URLs to PDF.

using IronPdf;

var renderer = new ChromePdfRenderer();

// Configure network authentication
renderer.LoginCredentials = new ChromeHttpLoginCredentials
{
    NetworkUsername = "user@domain.com",
    NetworkPassword = "securePassword",
    AuthenticationType = ChromeHttpLoginCredentials.AuthType.Basic
};

var pdf = renderer.RenderUrlAsPdf("https://intranet.company.com/reports");
pdf.SaveAs("authenticated-report.pdf");
using IronPdf;

var renderer = new ChromePdfRenderer();

// Configure network authentication
renderer.LoginCredentials = new ChromeHttpLoginCredentials
{
    NetworkUsername = "user@domain.com",
    NetworkPassword = "securePassword",
    AuthenticationType = ChromeHttpLoginCredentials.AuthType.Basic
};

var pdf = renderer.RenderUrlAsPdf("https://intranet.company.com/reports");
pdf.SaveAs("authenticated-report.pdf");
$vbLabelText   $csharpLabel

Cookies and HTTP Headers

For token-based or session-based authentication, attach custom cookies and HTTP headers directly to the rendering request.

using IronPdf;

var renderer = new ChromePdfRenderer();

// Add session cookies
renderer.RenderingOptions.CustomCookies["sessionId"] = "abc123token";
renderer.RenderingOptions.CustomCookies["authToken"] = "bearer-xyz";

// Add custom HTTP headers (e.g., API key or Bearer token)
renderer.RenderingOptions.CustomHttpRequestHeaders["Authorization"] = "Bearer eyJhbGciOi...";

var pdf = renderer.RenderUrlAsPdf("https://app.example.com/dashboard");
pdf.SaveAs("dashboard.pdf");
using IronPdf;

var renderer = new ChromePdfRenderer();

// Add session cookies
renderer.RenderingOptions.CustomCookies["sessionId"] = "abc123token";
renderer.RenderingOptions.CustomCookies["authToken"] = "bearer-xyz";

// Add custom HTTP headers (e.g., API key or Bearer token)
renderer.RenderingOptions.CustomHttpRequestHeaders["Authorization"] = "Bearer eyJhbGciOi...";

var pdf = renderer.RenderUrlAsPdf("https://app.example.com/dashboard");
pdf.SaveAs("dashboard.pdf");
$vbLabelText   $csharpLabel

TipsFor HTML form-based logins (POST username/password), consider using HttpClient to authenticate first, then pass the resulting cookies to the CustomCookies dictionary for rendering the protected page.

RELATED HOW-TO Article: How to Convert HTML Behind Login Authentication to PDF

4. How to Deploy HTML to PDF on Cloud Platforms

Deploying HTML to PDF conversion in cloud environments requires specific configuration for headless rendering, temporary file paths, and resource allocation. This section covers the most common cloud platforms and containerized deployments with IronPDF.

Platform Min Resources Package AutoConfig Temp Path Key Gotcha
Azure App Service B1 tier (Basic) IronPdf.Linux true /tmp Free/Shared tiers fail — no GPU, low memory
Azure Functions (Windows) B1 tier IronPdf true /tmp Uncheck "Run from package file"
AWS Lambda 512 MB / 330s timeout IronPdf.Linux true /tmp (required) Default filesystem is read-only
Docker (Ubuntu/Debian) Image-dependent IronPdf.Linux false Image default Set false — Dockerfile handles deps

How to Deploy on Azure

When deploying to Azure Functions or App Service, disable GPU acceleration and ensure your hosting tier provides enough memory for Chrome-based rendering. Add these settings at application startup, before any rendering calls.

Azure sandboxes run headless with no GPU access, and Free/Shared tiers (F1, D1) lack the resources Chrome requires. Target a B1 (Basic) tier or higher.

using IronPdf;

// Azure sandboxes block GPU access — always disable
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;
// Required on non-GUI Linux systems
IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = true;

var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Azure PDF Report</h1>");
pdf.SaveAs("azure-report.pdf");
using IronPdf;

// Azure sandboxes block GPU access — always disable
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;
// Required on non-GUI Linux systems
IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = true;

var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Azure PDF Report</h1>");
pdf.SaveAs("azure-report.pdf");
$vbLabelText   $csharpLabel

CautionAzure App Service Free and Shared tiers (F1, D1) do not have enough resources for Chrome-based PDF rendering. Use at minimum a B1 (Basic) tier or higher to avoid out-of-memory errors and process timeouts.

RELATED GET-STARTED Guide: How to Deploy IronPDF on Azure

How to Deploy on AWS Lambda

AWS Lambda requires Docker-based deployment for Chrome-based PDF rendering. The default Lambda filesystem is read-only, so all temp and deployment paths must point to /tmp.

Configure these settings at the top of your function handler, before any rendering calls.

using Amazon.Lambda.Core;
using IronPdf;

public class PdfFunction
{
    public string FunctionHandler(string input, ILambdaContext context)
    {
        // Lambda's only writable directory
        var tmpPath = "/tmp/";

        IronPdf.Installation.TempFolderPath = tmpPath;
        IronPdf.Installation.CustomDeploymentDirectory = tmpPath;
        IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;
        // Let IronPDF install Chrome dependencies on first cold start
        IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = true;

        context.Logger.LogLine("Rendering PDF...");

        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf(input);

        // Save to /tmp before uploading to S3 or returning
        var outputPath = $"{tmpPath}output.pdf";
        pdf.SaveAs(outputPath);

        return outputPath;
    }
}
using Amazon.Lambda.Core;
using IronPdf;

public class PdfFunction
{
    public string FunctionHandler(string input, ILambdaContext context)
    {
        // Lambda's only writable directory
        var tmpPath = "/tmp/";

        IronPdf.Installation.TempFolderPath = tmpPath;
        IronPdf.Installation.CustomDeploymentDirectory = tmpPath;
        IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;
        // Let IronPDF install Chrome dependencies on first cold start
        IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = true;

        context.Logger.LogLine("Rendering PDF...");

        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf(input);

        // Save to /tmp before uploading to S3 or returning
        var outputPath = $"{tmpPath}output.pdf";
        pdf.SaveAs(outputPath);

        return outputPath;
    }
}
$vbLabelText   $csharpLabel

Please noteConfigure your Lambda function with at least 512 MB of memory and a 60-second timeout minimum. Chrome-based rendering is memory-intensive, and cold starts require additional initialization time for the embedded browser engine.

RELATED GET-STARTED Guide: How to Deploy IronPDF on AWS Lambda

How to Deploy with Docker

For Docker deployments, use the IronPdf.Linux NuGet package to reduce image size and avoid runtime asset downloads. This package includes pre-bundled Linux-native binaries optimized for containerized environments.

Set LinuxAndDockerDependenciesAutoConfig = false when your Dockerfile already installs Chrome's shared-library dependencies via apt-get. The runtime auto-install is redundant in that case and can cause permission errors or longer cold starts.

Platform Package Key Configuration
Ubuntu 22.04 / Debian IronPdf.Linux Default — works out of the box
Alpine Linux IronPdf.Linux Install chromium via apk in Dockerfile
Amazon Linux 2 IronPdf.Linux Use LinuxAndDockerDependenciesAutoConfig = true
Windows Containers IronPdf No additional configuration required


A minimal multi-stage Dockerfile for an Ubuntu/Debian-based image:

FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /app
COPY . .
RUN dotnet publish -c Release -o /out

FROM mcr.microsoft.com/dotnet/aspnet:8.0
# Install Chrome dependencies for PDF rendering
RUN apt-get update && apt-get install -y \
    libglib2.0-0 libnss3 libatk1.0-0 libatk-bridge2.0-0 \
    libcups2 libdrm2 libxkbcommon0 libxcomposite1 \
    libxdamage1 libxrandr2 libgbm1 libpango-1.0-0 \
    libcairo2 libasound2 libxshmfence1 && \
    rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY --from=build /out .
ENTRYPOINT ["dotnet", "MyApp.dll"]


using IronPdf;

// Dependencies handled by Dockerfile apt-get — disable runtime install
IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = false;
// No GPU in containers
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;

var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Dockerized PDF</h1>");
pdf.SaveAs("output.pdf");
using IronPdf;

// Dependencies handled by Dockerfile apt-get — disable runtime install
IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig = false;
// No GPU in containers
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Disabled;

var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Dockerized PDF</h1>");
pdf.SaveAs("output.pdf");
$vbLabelText   $csharpLabel

RELATED GET-STARTED Guide: How to Use IronPDF with Docker

5. Compare IronPDF with Other .NET PDF Libraries

IronPDF is the solution of choice for many teams when it comes to C# PDF generation thanks to its robust Chromium-powered rendering engine, intuitive APIs and frequent product enhancements. Let’s compare IronPDF with other PDF converters to find the best fit for your PDF generation needs.

Quick Decision Matrix: IronPDF versus Other .NET PDF Converters

Solution When to use Best for
IronPDF Converting modern websites/HTML to PDF with exact visual fidelity. Enterprise applications requiring reliable HTML rendering engine, dynamic content, and professional support.
wkhtmltopdf Simple HTML conversion in non-critical applications where outdated rendering is acceptable. Basic document generation with legacy HTML/CSS.
Syncfusion When already invested in Syncfusion ecosystem or eligible for free community license. Organizations using multiple Syncfusion components.
Aspose.PDF Complex PDF manipulation when HTML rendering quality is less critical. Extensive PDF editing features beyond HTML conversion.

Please note: Solutions like PDFSharp and iTextSharp lack native HTML to PDF conversion capabilities and were excluded from this comparison. QuestPDF requires a code-first approach with no HTML support. Developers using these libraries must rely on third-party tools for HTML rendering.

RELATED COMPARISONS:

Detailed Comparison: IronPDF versus Other .NET PDF Converters

Feature ★ RecommendedIronPDF wkhtmltopdf iText 7 Aspose.PDF Syncfusion Apryse SelectPdf Spire.PDF PDFsharp QuestPDF
Rendering & Conversion
Rendering Accuracy Pixel-Perfect Best Print-Style Programmatic Only Good Good Good Good Low-Level No Rendering Code-First Layout
HTML5 Support Full Outdated Add-on Partial Full Module Full Limited No No (Code-First)
CSS3 Support Full Limited Add-on Partial Full Module Full Limited No No (Code-First)
JavaScript Execution Full Best No No Disputed Limited Limited Limited Very Limited No No
HTML→PDF (Modern Layout) Embedded Chromium Best Qt WebKit (Outdated) Paid Add-on Partial; JS Disputed Blink Engine Requires Module Full HTML→PDF Image-Based No Not an HTML Renderer
PDF→Image Rendering Yes No Separate Module Separate Product Yes Yes No Limited No Own Docs Only
Document Operations
Generate PDFs Programmatically Yes No Yes Yes Yes Yes HTML Only Yes Basic Yes (Fluent API)
Merge, Split & Rearrange Yes No Yes Yes Yes Yes Yes Yes Limited Yes
Headers / Footers / Page Numbers HTML/Text/Image Best Limited Yes Via Events Via Events Yes Templates Manual Manual Only First-Class Slots
Watermarks & Stamping Text & Image No Yes Yes Yes Yes Yes Limited No Yes (Overlays)
Extract Text from PDFs Yes No Yes Yes Yes Yes Yes Yes Basic No
OCR for Scanned PDFs Via IronOCR Integrated No Add-on Separate Product Add-on Add-on No Workaround No No
Security & Compliance
Digital Signatures Yes No Yes Yes Yes Sample Code Yes No No Not Documented
PDF/A Compliance Yes (PDF/A-3B) No Full PDF/A Validate & Create Requires Native SDK PDFACompliance No Yes Limited PDF/A-2x & 3x
Platform & Developer Experience
Cross-Platform Windows · Linux · macOS All 3 Depends on Binaries .NET Standard 2.0 Linux Extra Setup Blink + .NET Server Native SDK Windows-Only * Limited Linux Docs Windows-Focused Win/Linux/macOS
Cloud & Docker Deploy Azure · AWS · Docker Best Complex; Legacy Multiple Packages Partial; Containers Blink Extras Needed Native Deps Windows-Only Limited Info Simple; Lightweight Docker/K8s; Local
Support & Documentation
Documentation Extensive + Copy/Paste Best Partial CLI Docs Extensive; KB Broad; GitHub Help Center Cross-Language Catalog Getting Started Guides Program Guide Community Guides Structured + Companion App
Developer Support 24/7 Engineers Best Community Only Subscription Included Forum + Paid 24/5 Direct-Trac Commercial Email Forum + Email Community Only Community + GitHub
Licensing & Pricing
License Model Perpetual Open Source AGPL / Subscription Perpetual Annual Subscription Custom / Consumption Perpetual Annual Subscription Free (MIT) MIT Free / Paid Tiers
Starting Price $749+Perpetual · 1 Developer Free ~$45K/yrCustom Quote $1,175+Per Developer $995/yrSubscription · Free <$1M ~$9K+/yrCustom Quote $499+Perpetual $999/yrAnnual Subscription Free FreeCommunity MIT <$1M
Free Trial 30 Days · Full Features No Limits N/A (Free) 30 Days Yes (Watermarked) Community <$1M Rev Yes Community (5 Pages) Free (10 Pages) N/A (Free) N/A (MIT Free <$1M)
Pricing Transparency Published & Clear Best Open Source Complex AGPL Many Tiers Contact for Quote No Published Pricing Published Published MIT; No Restrictions MIT; Trust-Based

Real-life HTML to PDF Conversion Comparison: Rendering Reddit's Homepage

To evaluate the output PDF quality, we tested these libraries with Reddit's homepage containing dynamic web content, modern CSS, and JavaScript HTML elements. This page serves as an ideal test case for output PDF generation.

https://www.reddit.com/

Screenshot of Reddit homepage showing dynamic content, modern styling, and interactive elements used for PDF conversion testing

IronPDF

IronPDF conversion result showing pixel-perfect rendering of Reddit homepage with all dynamic content, styling, and interactive elements preserved

IronPDF delivers pixel-perfect results, preserving all dynamic web content, modern web fonts styling, and interactive elements exactly as displayed in Chrome, all in just a few lines of code.

Syncfusion

Syncfusion PDF conversion showing partial rendering with missing sections and incomplete styling of Reddit homepage

Syncfusion rendered PDF with most sections and styling missing, especially dynamic content. Initially blocked by Reddit's security. Achieving better results requires extensive command-line tuning, yet output remains incomplete.

Aspose.PDF

Aspose.PDF conversion attempt showing minimal content capture with most page elements missing from Reddit homepage

Aspose.PDF required manual HTML download first (no direct URL support). After conversion, output lacked proper formatting and missed nearly all content sections, making it unsuitable for modern web with dynamic content.

wkhtmltopdf

wkhtmltopdf output displaying static, unstyled version of Reddit homepage without dynamic elements or modern CSS

wkhtmltopdf completed quickly but produced a plain, static page missing critical content like live updates, dynamic elements, and interactive sections. This demonstrates wkhtmltopdf's incompatibility with modern, JavaScript-driven websites.

Conclusion on Performance and Output PDF Quality

For .NET developers needing a reliable HTML to PDF converter, IronPDF stands out with minimal code, easy-to-use APIs, and frequent product enhancements.

In a real-world test on web content, it delivered the fastest, most accurate results while Syncfusion lagged behind, Aspose required extra steps, and wkhtmltopdf missed modern styling. IronPDF offers the best balance of speed, accuracy, and simplicity for today’s HTML to PDF conversion workflows.

Please note: Aspose, SyncFusion, and wkhtmltopdf are trademarks of their respective owners. This site is not affiliated with or endorsed by them. All names, logos, and brands belong to their owners, and comparisons are based on publicly available information at the time of writing.

Summary

This guide covered everything needed to convert HTML to PDF in .NET: from basic string conversion to advanced features like async processing, digital signatures, and batch generation. We demonstrated three conversion methods, essential configurations, advanced features and security settings, and compared IronPDF with other libraries through real-world testing of dynamic document generation.

While competitors struggled with modern websites or required complex workarounds, IronPDF delivered flawless results with minimal code and powerful rendering engine.

Ready to streamline your PDF workflow and experience versatile PDF generation in just a few lines of code? Install IronPDF through NuGet Package Manager (or select Manage NuGet Package in Visual Studio) and convert your first HTML to PDF today.

Start your free 30-day trial for production testing without watermarks. Flexible licensing starts at $799 with transparent team pricing that scales with your needs.

View IronPDF Licensing

6. Troubleshooting & Technical Support

Having trouble with the following errors in HTML to PDF conversion? IronPDF offers 24/7 engineer support via the chat widget on https://ironpdf.com/

Quick Fixes on Common Errors

  • Slow first render? Normal. Chrome initializes in 2–3s, then speeds up.
  • Cloud issues? Use at least Azure B1 or equivalent resources.
  • Missing assets? Set base paths or embed as base64.
  • Missing elements? Add RenderDelay for JavaScript execution.
  • Memory in rendering? Update to v2025.9.4 for fixes in HTML to PDF, stamps, and headers/footers.
  • Form field issues (e.g., long textareas, checkboxes)? Fixed in v2025.7.17; ensure unique names for checkboxes.
  • Custom header/footer clipping or special characters corrupted? Resolved in v2025.8.8; test word-wrapping and metadata.

Get Help From The Engineers Who Built IronPDF, 24/7

Next Steps

How to Merge or Split PDF Documents
See How-To
How to Add Custom Headers and Footers to PDF Files
See How-To
How to Redact Text and Regions in PDF
See How-To

Frequently Asked Questions

How do I convert HTML to PDF in C#?

You can convert HTML to PDF in C# using a Chrome-rendering library that turns HTML, CSS3, and JavaScript into pixel-perfect PDFs. Tools like IronPDF let you render from URLs, HTML strings, or files while supporting headers, authentication, and print settings.

What is the best HTML to PDF library for .NET?

The best library should support accurate Chrome rendering, cross-platform deployment, and enterprise features. IronPDF covers all of these — running on Windows, Linux, macOS, and Docker, with support for security, signatures, compliance, and scalable .NET applications.

How can I convert HTML strings to PDF using C#?

To convert HTML strings to PDF, use the ChromePdfRenderer class and its RenderHtmlAsPdf method. Pass your HTML string to this method, then save the PDF using SaveAs.

What are the steps to convert a web page URL to a PDF document in C#?

You can convert a web page URL directly into a PDF by using the RenderUrlAsPdf method, which allows you to preserve styling, images, and interactive elements like forms and hyperlinks.

How do I convert an HTML file to PDF in C#?

Use ChromePdfRenderer.RenderHtmlFileAsPdf("path/to/file.html") to convert local HTML files to PDF. IronPDF resolves all relative asset paths (images, CSS, JS) automatically.

How do I convert ASP.NET Razor Pages or MVC Views to PDF?

IronPDF provides dedicated extension packages — IronPdf.Extensions.Razor for Razor Pages and IronPdf.Extensions.Mvc.Core for MVC Views. Use RenderRazorToPdf or RenderRazorViewToPdf with dependency injection to convert views directly to PDF from your controllers. See Razor guide →

How do I ensure JavaScript content is correctly rendered in the PDF?

Enable JavaScript rendering by setting RenderingOptions.EnableJavaScript = true and add a render delay using RenderingOptions.WaitFor.RenderDelay to ensure dynamic content is fully loaded before conversion. See WaitFor guide →

What is the best method to add headers and footers to a PDF in C#?

Use the TextHeaderFooter class for simple text headers and footers, or the HtmlHeaderFooter class for more complex HTML content. You can include dynamic placeholders such as {page}, {total-pages}, and {date} for automatic content generation. See headers & footers guide →

How do I manage page breaks in the PDF output in C# .NET?

Control page breaks in your PDFs by using CSS properties like page-break-after: always and page-break-inside: avoid within a print media type CSS block. See page breaks guide →

What options are available for setting paper size and orientation in PDFs?

Set the paper size using RenderingOptions.PaperSize (options include A4, Letter, Legal, etc.) and the orientation with RenderingOptions.PaperOrientation for Portrait or Landscape. Custom sizes in millimeters or inches are also supported. See paper size guide →

Can I convert authenticated web pages to PDF?

Yes. IronPDF supports cookies, custom HTTP headers, and form-based authentication. Set cookies via ChromePdfRenderer.RenderingOptions.CustomCookies, or pass auth headers for token-based authentication. Windows NTLM and Kerberos authentication are also supported. See cookies guide →

Can I create multiple PDFs from a single HTML template in C#?

Yes, create HTML templates with placeholders, then use string replacement or templating libraries like Handlebars.NET. Replace placeholders with actual values in your looped data, and generate PDFs using RenderHtmlAsPdf.

Is it possible to secure my generated PDFs with a password?

Yes, you can use the SecuritySettings property to set user and owner passwords, configure permissions like printing and copying, and apply AES256 encryption with SecuritySettings.EncryptionAlgorithm. See encryption guide →

Can I generate PDF/A compliant documents from HTML?

Yes. IronPDF supports PDF/A-1b, PDF/A-2b, PDF/A-3b and PDF/UA standards for archival and accessibility compliance, which most HTML-to-PDF converters do not offer. See PDF/A guide →

How can I optimize the performance for generating a large volume of PDFs?

Optimize performance by using async methods like RenderHtmlAsPdfAsync for non-blocking operations. Reuse ChromePdfRenderer instances, process multiple PDFs concurrently using Task.WhenAll, and ensure you have adequate server resources on a 64-bit system. See async guide →

How can I merge multiple PDFs or include a cover page in my document?

Use the static PdfDocument.Merge method to combine multiple PDFs. Generate your cover page separately and merge it with your main document to create a comprehensive PDF. See merge guide →

Can I deploy IronPDF on Azure, AWS, or Docker?

Yes. IronPDF runs on Azure App Service, Azure Functions, AWS Lambda, and Docker containers on Linux. Dedicated setup guides and Docker images are available for each platform. See Azure guide → · See AWS guide → · See Docker guide →

.NET 10 Compatibility: Does IronPDF support .NET 10 right away?

Yes — IronPDF is fully compatible with .NET 10. According to IronPDF release notes, the library is day-one ready for .NET 10 projects, with zero extra configuration needed. Whether you're using web, console, desktop, or microservices applications, IronPDF works "out of the box" with .NET 10.

Is IronPDF free to use?

IronPDF offers a free 30-day trial with full functionality and no watermarks on development. Production use requires a commercial license starting at $749. Lite, Plus, Professional, and Enterprise tiers are available. See pricing →

How does this library's rendering quality compare to other options like wkhtmltopdf?

This library uses a modern Chrome rendering engine for pixel-perfect PDFs, unlike wkhtmltopdf's outdated WebKit engine. It doesn't require server executables, supports full JavaScript/CSS3, receives regular updates, and offers professional support.

Why should I choose this library over PDFSharp for HTML to PDF conversion?

PDFSharp lacks built-in HTML to PDF conversion, requiring complex workarounds. This library offers direct HTML/URL/file conversion with a high-level API, support for modern web technologies, and regular updates with professional support. See PDFSharp comparison →

What makes this a better choice than iTextSharp for HTML conversion?

The free version of iTextSharp doesn't support native HTML to PDF conversion and has a complex low-level API. This library provides seamless HTML conversion with an intuitive API, full CSS3/JavaScript support, and no AGPL licensing restrictions. See iTextSharp comparison →

How does this library's rendering quality compare to Aspose.PDF?

This library produces pixel-perfect Chrome-quality PDFs, whereas Aspose.PDF often misses styling and dynamic content. Aspose requires manual HTML downloads for URL conversion, but this library converts URLs directly with superior accuracy. See Aspose comparison →

Why might I choose this library over Syncfusion PDF?

While Syncfusion is capable, this library's optimized Chrome engine performs faster and handles dynamic content more effectively. It offers a simpler API and additional features like OCR and barcode generation. See Syncfusion comparison →

Jacob Mellor, Chief Technology Officer @ Team Iron
Chief Technology Officer

Jacob Mellor is Chief Technology Officer at Iron Software and a visionary engineer pioneering C# PDF technology. As the original developer behind Iron Software's core codebase, he has shaped the company's product architecture since its inception, transforming it alongside CEO Cameron Rimington into a 50+ person company serving NASA, Tesla, ...

Read More
Reviewed by
Jeff Fritz
Jeffrey T. Fritz
Principal Program Manager - .NET Community Team
Jeff is also a Principal Program Manager for the .NET and Visual Studio teams. He is the executive producer of the .NET Conf virtual conference series and hosts 'Fritz and Friends' a live stream for developers that airs twice weekly where he talks tech and writes code together with viewers. Jeff writes workshops, presentations, and plans content for the largest Microsoft developer events including Microsoft Build, Microsoft Ignite, .NET Conf, and the Microsoft MVP Summit
Ready to Get Started?
Nuget Downloads 17,803,474 | Version: 2026.3 just released
Still Scrolling Icon

Still Scrolling?

Want proof fast? PM > Install-Package IronPdf
run a sample watch your HTML become a PDF.