IRONSOFTWAREHOME

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

Jacob Mellor, Chief Technology Officer @ Team Iron
Jacob Mellor
Updated: September 5, 2026

This complete tutorial covers strings, URLs, files, deployment, and scaling. To get started, install IronPDF from NuGet and call ChromePdfRenderer.RenderHtmlAsPdf(). Three lines of code would be enough to produce a pixel-perfect PDF. IronPDF's Chrome-based engine handles the rendering, deployment, and scaling limits that trip up simpler tools. If you are still choosing a library, compare all C# HTML to PDF libraries first.

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. 1Install IronPDF with NuGet Package Manager

    PM > Install-Package IronPdf

  2. 2Copy and run this code snippet.

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

    Start using IronPDF in your project today with a free trial
    arrow pointer

All code in this guide was verified on IronPDF v2026.8.1 · .NET 10 · July 2026.

Why Convert HTML to PDF?

Converting HTML to PDF lets your team build documents with the web stack it already knows, rather than learning a separate PDF layout API. A few reasons it works well:

  • Reuse the design language you already know: Lay out documents in the HTML and CSS you write every day instead of a proprietary PDF drawing API.
  • Reuse existing web templates: The templates already behind your web app become PDF sources, so developers write less bespoke PDF code.
  • Clean split of work: Designers can own the look end-to-end while developers own rendering and wiring it into the application.
  • One pipeline, many document types: The same approach covers invoices, reports, receipts, and archives without a separate tool for each.
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: uses Chrome's Blink engine for accurate HTML to PDF conversion.
  • Pixel-Perfect Accuracy: generated PDFs match the web precisely, not a printer-friendly version.
  • Full Modern Web Support: complete CSS3, HTML5, and JavaScript support for all HTML elements.
  • 5-20x Performance Boost: significantly faster than browser automation or web drivers.
  • PDF/UA Compliance: accessible PDF generation that meets Section 508 standards.
  • No External Dependencies: no executables to install on servers.
  • ✅ Designed for C#, F#, and VB.NET on .NET 10, 9, 8, 7, 6, Core, Standard, and Framework.
Please note: Latest in v2026.8.1 (June 2026): access to PDF Optional Content Groups (layers) with layer hierarchy and visibility metadata, a new CSS page-rule policy and header/footer overlap detection for cleaner margin handling, greater engine stability under heavy load and constrained-CPU environments, more accurate PDF redaction with corrected signature timestamps across daylight-saving changes, and clearer, actionable errors when PDF generation stalls. See the full changelog for the complete release history.

IronPDF gives .NET developers a straightforward way to turn their web application's HTML into professional-looking PDFs. 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
Choose Your HTML to PDF Path by Use Case

Not sure where to start? Jump straight to the path that matches what you're building:

What you're buildingStart here
Converting a one-off HTML stringHTML String to PDF
Archiving a live URL or web pageURL to PDF
Building a Razor Pages or MVC appRazor / MVC to PDF
Batch or high-volume server-side generationAsync & batch generation
Needing a code-first layout engine (no HTML) or a zero-budget open-source routeFree & Open-Source Alternatives

1. How to Convert HTML to PDF C#

Whether you're working with HTML strings, URLs, or HTML files, IronPDF gives you flexible options for producing high-quality PDFs.

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:

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.

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");

Output

Run the snippet above and IronPDF returns a one-page PDF holding exactly the heading you passed in, the simplest possible render:

Performance

The performance of IronPDF's conversion to PDF from string, URL, and HTML was measured using a Lenovo laptop with 16GB RAM. The test document is a 3-page enterprise invoice with standard CSS Grid, gradients and multi-section tables.

The results are as follows:

MetricValue
Average render time~486 ms
Memory per render~3.6 MB

Measured across 5 successive renders on an 8-core / 16-thread laptop (Windows 11, .NET 8). The first call also includes one-time Chromium engine initialization (~1.3 s)

The first time I ran the test, render time was sluggish (Over a second per call!). After looking at what was happening, I realized I had several open Chromium instances running and was on battery power, neither of which let the library show its real speed. Once I closed the competing processes and plugged in, things sharpened up: warm runs averaged ~486 ms with the fastest landing near 473 ms.

Tips: 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 baseUrlOrPath 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");
Tips: baseUrlOrPath tells IronPDF where to find your CSS, JavaScript, and image files. All relative paths in your HTML string will be resolved from this directory.
Warning: One issue to keep an eye out for, and why testing the output is important regardless of what library you use for automated document generation, is that the enterprise document may have broken elements or missing assets when references default back to system settings. IronPDF gives you the baseUrlOrPath parameter to point relative paths at the right directory, so a quick output check before bulk runs is usually all you need to catch it.

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.

The core method is RenderUrlAsPdf, which fetches a live page and renders it in a single call:

using IronPdf;

// Create a PDF from any existing web page
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/PDF");
pdf.SaveAs("wikipedia.pdf");

Output

Here RenderUrlAsPdf captures a live Wikipedia article into a static, print-ready PDF, with text, images, tables, and layout preserved across all 33 pages:

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

JavaScript Support

IronPDF fully supports JavaScript, jQuery, and even AJAX. For dynamic content, you can configure IronPDF to wait for JavaScript to finish before rendering. 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

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://observablehq.com/@d3/chord-diagram");

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

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;

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 method is best for converting templates or pre-designed HTML pages.

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

Output

Point RenderHtmlFileAsPdf at an HTML invoice template and the file's full design (logo, line-item table, totals) comes through pixel-perfect, with no extra code on your side:

Performance

Performance was measured again by keeping all variables constant to render the previous 3-page enterprise invoice from a file on disk:

MetricValue
Average render time~502 ms
Memory per render~3.1 MB

Measured across 5 successive renders on the same 8-core / 16-thread laptop (Windows 11, .NET 8). File-based rendering matches in-memory string rendering within about 3%; reading the HTML from disk adds no measurable overhead.

Tips: Keep 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

using IronPdf;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

public class ReportModel : PageModel
{
    public IActionResult OnGet()
    {
        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");
    }
}
Please note: RenderRazorToPdf 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

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>();

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

using IronPdf;
using IronPdf.Extensions.Mvc.Core;
using Microsoft.AspNetCore.Mvc;

public class ReportController : Controller
{
    private readonly IRazorViewRenderer _viewRenderService;

    // Inject the view renderer via constructor
    public ReportController(IRazorViewRenderer viewRenderService)
    {
        _viewRenderService = viewRenderService;
    }

    public IActionResult Download()
    {
        var reportModel = new { Title = "Quarterly Report", Total = 1250.00 };
        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");
    }
}

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

Dynamic Web Page to PDFs

Do you need your dynamic web page preserved and converted to PDFs while preserving the exact layout and formatting? Look no further than IronPDF, which quickly converts a variety of popular dynamic web page frameworks to PDFs.

PDF from ASPX Pages

Here's a brief code snippet on converting ASPX Pages as PDF in Active Server Pages.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using IronPdf;

namespace AspxToPdfTutorial
{
    public partial class Invoice : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            IronPdf.AspxToPdf.RenderThisPageAsPdf(IronPdf.AspxToPdf.FileBehavior.InBrowser);
        }
    }
}

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

XAML to PDF (MAUI)

For developers looking to build cross-platform applications, .NET MAUI is a popular choice among the frameworks. IronPDF fully supports converting XAML to PDF with a few steps.

using IronPdf.Extensions.Maui;

namespace mauiSample;

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
    }

    private void PrintToPdf(object sender, EventArgs e)
    {
        ChromePdfRenderer renderer = new ChromePdfRenderer();

        // Apply HTML header
        renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
        {
            HtmlFragment = "<h1>Header</h1>",
        };

        // Render PDF from Maui Page
        PdfDocument pdf = renderer.RenderContentPageToPdf<MainPage, App>().Result;

        pdf.SaveAs(@"C:\Users\lyty1\Downloads\contentPageToPdf.pdf");
    }
}

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Generate PDF Reports

When it comes to generating PDF Reports, the exact dimensions and format are crucial. As such, IronPDF allows you to generate PDFs seamlessly with only a couple of steps.

using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();

renderer.RenderHtmlFileAsPdf("report.html").SaveAs("report.pdf");

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Create PDFs in Blazor Servers

IronPDF supports .NET 6, and as it includes project types like Blazor, this code snippet provides a brief example of how to create PDFs in Blazor Server.

@code {

    // Model to bind user input
    private InputHTMLModel _InputMsgModel = new InputHTMLModel();

    private async Task SubmitHTML()
    {
        // Set your IronPDF license key
        IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";

        // Create a renderer to convert HTML to PDF
        var render = new IronPdf.ChromePdfRenderer();

        // Render the HTML input into a PDF document
        var doc = render.RenderHtmlAsPdf(_InputMsgModel.HTML);

        var fileName = "iron.pdf";

        // Create a stream reference for the PDF content
        using var streamRef = new DotNetStreamReference(stream: doc.Stream);

        // Invoke JavaScript function to download the PDF in the browser
        await JS.InvokeVoidAsync("SubmitHTML", fileName, streamRef);
    }

    public class InputHTMLModel
    {
        public string HTML { get; set; } = "My new message";
    }
}

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Razor to PDF (Blazor Servers)

Aside from creating PDFs in Blazor Servers, IronPDF also supports generating PDF documents from Razor components within a Blazor page. Making the creation of PDF files and pages much more streamlined.

[Parameter]
public IEnumerable<PersonInfo> persons { get; set; }
public Dictionary<string, object> Parameters { get; set; } = new Dictionary<string, object>();
 
protected override async Task OnInitializedAsync()
{
    persons = new List<PersonInfo>
    {
        new PersonInfo { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
        new PersonInfo { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
        new PersonInfo { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
    };
}
private async void PrintToPdf()
{
    ChromePdfRenderer renderer = new ChromePdfRenderer();
 
    // Apply text footer
    renderer.RenderingOptions.TextFooter = new TextHeaderFooter()
        {
            LeftText = "{date} - {time}",
            DrawDividerLine = true,
            RightText = "Page {page} of {total-pages}",
            Font = IronSoftware.Drawing.FontTypes.Arial,
            FontSize = 11
        };
 
    Parameters.Add("persons", persons);
 
    // Render razor component to PDF
    PdfDocument pdf = renderer.RenderRazorComponentToPdf<Person>(Parameters);
 
    File.WriteAllBytes("razorComponentToPdf.pdf", pdf.BinaryData);
}

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

CSHTML to PDF

Converting CSHTML (Razor) to PDF allows you to generate professional, print-ready documents directly from your web applications. This is useful for invoices, reports, contracts, or any dynamic content. IronPDF supports Razor Pages, MVC Core, and MVC Framework, as well as headless rendering, making it seamless to integrate PDF generation into your .NET applications with just a few lines of code.

CSHTML to PDF (Razor Pages)
using IronPdf.Razor.Pages;
 
public IActionResult OnPostAsync()
{
    persons = new List<Person>
    {
    new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
    new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
    new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
    };
 
    ViewData["personList"] = persons;
 
    ChromePdfRenderer renderer = new ChromePdfRenderer();
 
    // Render Razor Page to PDF document
    PdfDocument pdf = renderer.RenderRazorToPdf(this);
 
    Response.Headers.Add("Content-Disposition", "inline");
 
    return File(pdf.BinaryData, "application/pdf", "razorPageToPdf.pdf");
}

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

CSHTML to PDF (MVC Core)
public async Task<IActionResult> Persons()
{
    var persons = new List<Person>
    {
    new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
    new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
    new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
    };
    if (_httpContextAccessor.HttpContext.Request.Method == HttpMethod.Post.Method)
    {
        ChromePdfRenderer renderer = new ChromePdfRenderer();
 
        // Render View to PDF document
        PdfDocument pdf = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Persons.cshtml", persons);
        Response.Headers.Add("Content-Disposition", "inline");
 
        // Output PDF document
        return File(pdf.BinaryData, "application/pdf", "viewToPdfMVCCore.pdf");
    }
    return View(persons);
}

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

CSHTML to PDF (MVC Framework)
public ActionResult Persons()
{
    var persons = new List<Person>
    {
    new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
    new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
    new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
    };
    if (HttpContext.Request.HttpMethod == "POST")
    {
        // Provide the path to your view file
        var viewPath = "~/Views/Home/Persons.cshtml";
        ChromePdfRenderer renderer = new ChromePdfRenderer();
 
        // Render Razor view to PDF document
        PdfDocument pdf = renderer.RenderView(this.HttpContext, viewPath, persons);
        Response.Headers.Add("Content-Disposition", "inline");
 
        // View the PDF
        return File(pdf.BinaryData, "application/pdf");
    }
    return View(persons);
}

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

CSHTML to PDF (Headlessly)
app.MapGet("/PrintPdf", async () =>
{
    // Set your IronPDF license key
    IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
    
    // Enable detailed logging for troubleshooting
    IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All;

    // Render the Razor view to an HTML string
    string html = await RazorTemplateEngine.RenderAsync("Views/Home/Data.cshtml");

    // Create a new instance of ChromePdfRenderer 
    ChromePdfRenderer renderer = new ChromePdfRenderer();
   
    // Render the HTML string as a PDF document
    PdfDocument pdf = renderer.RenderHtmlAsPdf(html, "./wwwroot");

    // Return the PDF file as a response
    return Results.File(pdf.BinaryData, "application/pdf", "razorViewToPdf.pdf");
});

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

2. How to Configure HTML to PDF Settings

IronPDF provides extensive customizations through the ChromePdfRenderer.RenderingOptions property.

SettingsDescriptionExample
PaperSizeSet page dimensions for existing PDFs (A4, Letter, Legal, etc.)PdfPaperSize.A4
PaperOrientationSet Portrait or Landscape for existing PDFsPdfPaperOrientation.Landscape
MarginTop/Bottom/Left/RightSet page margins in millimeters (default: 25mm)25
CssMediaTypeScreen or Print CSS for HTML to PDFPdfCssMediaType.Print
PrintHtmlBackgroundsInclude background colors/images (default: true)true
EnableJavaScriptExecute JavaScript before rendering HTML contenttrue
WaitFor.RenderDelayWait 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");
Tips: Use 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:

Rendering pages that require authentication? See How to Render Authenticated Pages to PDF for setting HTTP headers, cookies, and login credentials with runnable examples.

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
var 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");

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 methods let you generate documents at scale, protect sensitive files, and ensure document authenticity.

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>

For longer templates, 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");
}

HTML to PDF Templating with Handlebars.NET

For complex templates with loops and conditionals, use Handlebars.NET to render dynamic HTML content.

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

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>
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.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

public class PdfGenerationService
{
    // 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");
        }
    }
}
Tips: Performance 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 recent 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 PDF documents with passwords and permissions.

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 = PdfPrintSecurity.PrintLowQuality;

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

How to Add Digital Signatures to PDF Files

Add cryptographic signatures to ensure PDF document authenticity. Once signed, you can verify the signature and read the signer's certificate for audit and compliance checks.

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"
};

// Apply signature to PDF documents
pdf.Sign(signature);
pdf.SaveAs("signed-contract.pdf");
C#

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");
Warning: Each 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;

// Full page HTML containing the target element
string fullPageHtml = @"
<html>
<body>
    <header><h1>Acme Corp Invoice</h1></header>
    <div id='invoice-summary'>
        <h2>Invoice #12345</h2>
        <p>Total: $1,250.00</p>
    </div>
    <footer>Confidential</footer>
</body>
</html>";

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");

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. This enables rendering of intranet dashboards, restricted reports, or API-generated pages directly to PDF without needing to retrieve the HTML separately.

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");

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.HttpRequestHeaders["Authorization"] = "Bearer eyJhbGciOi...";

var pdf = renderer.RenderUrlAsPdf("https://app.example.com/dashboard");
pdf.SaveAs("dashboard.pdf");
C#
Tips: For 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 Articles: How to Convert HTML Behind Login Authentication to PDF | Custom HTTP Request Headers

How Do I Generate PDFs from Multiple HTML Snippets?

To generate PDFs by combining HTML snippets, you can merge them. This creates multi-section reports or combines content from different sources:

var renderer = new ChromePdfRenderer();

PdfDocument part1 = renderer.RenderHtmlAsPdf("<h1>Section 1</h1><p>First section content</p>");
PdfDocument part2 = renderer.RenderHtmlAsPdf("<h1>Section 2</h1><p>Second section content</p>");

var merged = PdfDocument.Merge(part1, part2);
merged.SaveAs("Merged.pdf");

// Alternative approach: copy specific pages
var combinedDoc = new PdfDocument();
combinedDoc.CopyPage(part1, 0); // Copy first page
combinedDoc.CopyPage(part2, 0); // Copy first page
combinedDoc.SaveAs("Combined.pdf");

This helps when creating multi-section reports from different HTML fragments. You can also add bookmarks to improve navigation.

Adobe Acrobat interface showing a PDF document with 'Section 1' heading and a Pages panel displaying thumbnails of Section 1 and Section 2.

How Do I Convert HTML to PDF in Web APIs?

In ASP.NET Web API, generate and return PDFs without saving to disk using MemoryStream. This pattern is ideal for Blazor applications and RESTful services:

[HttpGet("download")]
public IActionResult GetPdf()
{
    var renderer = new ChromePdfRenderer();
    string html = "<h1>Web Report</h1><p>Generated dynamically.</p>";

    var pdf = renderer.RenderHtmlAsPdf(html);
    var bytes = pdf.BinaryData;

    // Optional: Add metadata
    pdf.MetaData.Author = "API Service";
    pdf.MetaData.CreationDate = DateTime.Now;

    return File(bytes, "application/pdf", "report.pdf");
}

This pattern works great for server-side PDF generation in .NET 10 web applications. You can integrate with CSHTML views for MVC applications.

How Do You Add Headers, Watermarks, and Security?

Adding Professional Headers and Footers

Headers and footers that display page numbers, dates, or branding make multi-page documents far more readable and professional. IronPDF processes them as HTML fragments, so you can use full CSS styling including images and brand colors:

using IronPdf;

var renderer = new ChromePdfRenderer();

renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
    MaxHeight = 50,
    HtmlFragment = "<div style='text-align:center;font-size:12px;'>Annual Report 2025 -- Confidential</div>",
    BaseUrl = new Uri(@"file:///C:/assets/")
};

renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter
{
    MaxHeight = 30,
    HtmlFragment = "<div style='text-align:center;font-size:10px;'>Page {page} of {total-pages}</div>",
    DrawDividerLine = true
};

renderer.RenderingOptions.MarginTop = 60;
renderer.RenderingOptions.MarginBottom = 40;

var pdf = renderer.RenderHtmlAsPdf("<h1>Report Content</h1><p>Body text here.</p>");
pdf.SaveAs("report-with-headers.pdf");

Placeholders like {page} and {total-pages} are replaced automatically at render time. Review the headers and footers tutorial for dynamic date injection, logo placement, and alternating page styles.

Applying Watermarks, Encryption, and Digital Signatures

Watermarks protect draft documents and confidential reports. Password protection and permission settings restrict who can print, copy, or edit a PDF. Digital signatures add a verifiable authenticity layer for contracts and regulated documents. You can combine all three in a single workflow:

using IronPdf;
using System.Security.Cryptography.X509Certificates;

var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Contract Agreement</h1><p>Terms and conditions.</p>");

// Watermark
pdf.ApplyWatermark(
    "<div style='font-size:72px;color:red;opacity:0.3;'>DRAFT</div>",
    rotation: 45,
    opacity: 30
);

// Encryption and permissions
pdf.SecuritySettings.UserPassword = "user123";
pdf.SecuritySettings.OwnerPassword = "owner456";
pdf.SecuritySettings.AllowUserPrinting = IronPdf.Security.PdfPrintSecurity.NoPrint;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;

// Digital signature
var cert = X509CertificateLoader.LoadPkcs12FromFile("certificate.pfx", "password");
var signature = new PdfSignature(cert)
{
    SigningContact = "Jane Smith",
    SigningLocation = "New York, NY",
    SigningReason = "Contract Approval"
};
pdf.Sign(signature);
pdf.SaveAsRevision("signed-contract.pdf");

Learn about watermarking techniques, PDF security settings, and certificate-based signing including HSM integration for hardware security modules.

Security Considerations

When converting HTML supplied by users or external systems, validate the input before rendering. Sanitizing HTML helps prevent malicious scripts or unexpected content from being processed.

If your application loads external resources, restrict them to trusted domains whenever possible. Using HTTPS URLs for stylesheets, fonts, and images also improves reliability and security.

Testing the rendering process in your production environment is recommended because network configuration, authentication, resource availability, and the underlying operating system can affect the generated PDF; by contrast, PuppeteerSharp may require custom startup scripts for Azure App Service, which can complicate deployment compared with IronPDF.

My favorite library of this kind is IronPDF. It allows for fast and efficient manipulation of PDF files. It also has many valuable features, like exporting to PDF/A format and digitally signing PDF documents.

Milan Jovanovic

Microsoft MVP

View case study

IronOCR means we can save $40,000 annually from manual processing, while enhancing productivity and freeing up resources for high-impact tasks. I would highly recommend it.

Brent Matzelle

Chief Technology Officer, OPYN

View case study

The IronSuite play a crucial role in our operations. These are tools that increase efficiencies across the business including creating floor plans and improving inventory management.

David Jones

Lead Software Engineer, Agorus Build

View case study

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.

PlatformMin ResourcesPackageAutoConfigTemp PathKey Gotcha
Azure App ServiceB1 tier (Basic)IronPdf.Linuxtrue/tmpFree/Shared tiers fail (no GPU, low memory)
Azure Functions (Windows)B1 tierIronPdftrue/tmpUncheck "Run from package file"
AWS Lambda512 MB / 60s timeoutIronPdf.Linuxtrue/tmp (required)Default filesystem is read-only
Docker (Ubuntu/Debian)Image-dependentIronPdf.LinuxfalseImage defaultSet 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");
Caution: Azure 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;
    }
}
Please note: Configure 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.

PlatformPackageKey Configuration
Ubuntu 22.04 / DebianIronPdf.LinuxDefault, works out of the box
Alpine LinuxIronPdf.LinuxInstall chromium via apk in Dockerfile
Amazon Linux 2IronPdf.LinuxUse LinuxAndDockerDependenciesAutoConfig = true
Windows ContainersIronPdfNo additional configuration required

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

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

FROM mcr.microsoft.com/dotnet/aspnet:10.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"]
Text

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");

A real gotcha I came across with the Docker setup: IronPdfEngine (the Docker image) runs as a single instance, so the engine itself does not scale horizontally. The fix-around is simple. Any app using the IronPdf library, with or without IronPdfEngine, scales horizontally just by spinning up new instances, and the workload spreads across them quite easily.

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

How can HTML-to-PDF performance be optimized and scaled in .NET Core?

IronPDF's Chromium engine already renders quickly on modern hardware, but throughput can be multiplied by batching renders, enabling multi-threading, and trimming Headless Chrome overhead. The tips below apply equally to all .NET versions.

1. Batch renders on a background thread pool

IronPdf.License.LicenseKey = "YourLicenseKey";
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Set rendering options
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
renderer.RenderingOptions.PaperOrientation = IronPdf.Rendering.PdfPaperOrientation.Portrait;

renderer.RenderHtmlFileAsPdf(@"testFile.html").SaveAs("GeneratedFile.pdf");

2. Trim Headless Chrome startup cost

IronPDF ships its own Chromium build, but each render incurs a small startup tax. Pooling helps, and Linux containers must include two native libs:

RUN apt-get update && \
    apt-get install -y --no-install-recommends libnss3 libatk1.0-0
Text

Missing either library manifests as a libnss3.so not found error in Docker logs.

Recommended Chrome flags (automatically applied by IronPDF) include --disable-gpu and --no-sandbox to reduce memory and root-user issues in containers.

3. Wait for late JavaScript with RenderDelay or WaitFor

Pages that animate counters or fetch data after DOMContentLoaded may need a short delay:

renderer.RenderingOptions.RenderDelay = 200;        // ms
// OR: renderer.RenderingOptions.WaitFor.JavaScript("window.doneLoading === true");
C#

See the dedicated WaitFor tutorial for custom promises and DOM polling.

4. Enable debug logging for one request

IronPdf.License.LicenseKey = "YourLicenseKey";
PdfDocument pdf = PdfDocument.FromFile("1.pdf");
PdfDocument pdf2 = PdfDocument.FromFile("2.pdf");
pdf.AppendPdf(pdf2);
pdf.SaveAs("appendedFile.pdf");

Live DevTools traces expose missing fonts, 404 images, and timing events without re-compiling code.

5. Reuse template PDFs instead of re-rendering

For invoice runs, create a template PDF with placeholders like [[name]] and perform a text replace instead of rebuilding complex HTML. It avoids re-rendering complex HTML and is memory-light.

Further Reading


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.

Free and Open-Source Alternatives

Some tools that might come into consideration:

  • PuppeteerSharp: an MIT-licensed .NET port of Puppeteer that drives headless Chrome.
  • Playwright for .NET: Microsoft's Apache-2.0 automation library, also Chromium-based.
  • wkhtmltopdf: a long-standing standalone HTML-to-PDF binary.
  • Native browser routes: print-to-PDF straight from a headless browser or OS print driver.

A distinction worth drawing first: PuppeteerSharp and Playwright are browser-automation frameworks rather than PDF libraries. They expose a print-to-PDF call on top of real Chromium, so rendering fidelity is excellent, but PDF specifics like headers and footers, encryption, signatures, and PDF/A, along with the browser's lifecycle, are left to you: shipping and updating the Chromium binary, handling concurrency and crash recovery, and building document structure by hand. Playwright adds a constraint worth knowing early: its PdfAsync runs only in headless Chromium (not Firefox or WebKit), so deployments must guarantee a headless Chrome, which matters in containers and serverless.

wkhtmltopdf sits differently again. The project was archived in 2024, and its final release (0.12.6, 2020) runs a ~2012 Qt WebKit engine receiving no further security patches, including an unpatched critical SSRF advisory (CVE-2022-35583); it remains workable for simple static documents on trusted input, but less so for public-facing output. Native browser routes need no library at all, at the cost of any .NET-native PDF API or real control over server-side automation.

For prototypes, internal tools, and zero-budget work, these are legitimate choices. The comparison below covers the commercial libraries feature by feature.

Quick Decision Matrix: IronPDF versus .NET PDF Converters

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

RELATED COMPARISONS:

Detailed Comparison: IronPDF versus Other .NET PDF Converters

Feature★ RecommendedIronPDFwkhtmltopdfiTextAspose.PDFSyncfusionApryseSelectPdfSpire.PDFPDFSharpQuestPDF
Rendering & Conversion
Rendering AccuracyPixel-Perfect Print-StyleProgrammatic OnlyGoodGoodGoodGoodLow-LevelNo RenderingCode-First Layout
HTML5 SupportFullOutdatedAdd-onPartialFullModuleFullLimitedNoNo (Code-First)
CSS3 SupportFullLimitedAdd-onPartialFullModuleFullLimitedNoNo (Code-First)
JavaScript ExecutionFullNoNoDisputedLimitedLimitedLimitedVery LimitedNoNo
HTML→PDF (Modern Layout)Embedded Chromium Qt WebKit (Outdated)Paid Add-onPartial; JS DisputedBlink EngineRequires ModuleFull HTML→PDFImage-BasedNoNot an HTML Renderer
PDF→Image RenderingYesNoYesYesYesYesNoLimitedNoOwn Docs Only
Document Operations
Generate PDFs ProgrammaticallyYesNoYesYesYesYesHTML OnlyYesBasicYes (Fluent API)
Merge, Split & RearrangeYesNoYesYesYesYesYesYesLimitedYes
Headers / Footers / Page NumbersHTML/Text/Image LimitedYesVia EventsVia EventsYesTemplatesManualManual OnlyFirst-Class Slots
Watermarks & StampingText & ImageNoYesYesYesYesYesLimitedNoYes (Overlays)
Extract Text from PDFsYesNoYesYesYesYesYesYesBasicNo
OCR for Scanned PDFsVia IronOCR IntegratedNoAdd-onSeparate ProductAdd-onAdd-onNoWorkaroundNoNo
Security & Compliance
Digital SignaturesYesNoYesYesYesSample CodeYesNoNoNot Documented
PDF/A ComplianceYes (PDF/A-3B)NoFull PDF/AValidate & CreateRequires Native SDKPDFAComplianceNoYesLimitedPDF/A-2x & 3x
Platform & Developer Experience
Cross-PlatformWindows · Linux · macOS All 3Depends on Binaries.NET Standard 2.0Linux Extra SetupBlink + .NET ServerNative SDKWindows-Only *Limited Linux DocsWindows-FocusedWin/Linux/macOS
Cloud & Docker DeployAzure · AWS · Docker Complex; LegacyMultiple PackagesPartial; ContainersBlink Extras NeededNative DepsWindows-OnlyLimited InfoSimple; LightweightDocker/K8s; Local
Support & Documentation
DocumentationExtensive + Copy/Paste Partial CLI DocsExtensive; KBBroad; GitHubHelp CenterCross-Language CatalogGetting Started GuidesProgram GuideCommunity GuidesStructured + Companion App
Developer Support24/7 Support · 24/5 ChatCommunity OnlySubscription IncludedForum + Paid24/5 Direct-TracCommercialEmailForum + EmailCommunity OnlyCommunity + GitHub
Licensing & Pricing
License ModelPerpetualOpen SourceAGPL / SubscriptionPerpetualAnnual SubscriptionCustom / ConsumptionPerpetualPerpetualFree (MIT)MIT Free / Paid Tiers
Starting Price$999Perpetual · 1 DeveloperFree~$45K/yrCustom Quote$1,175+Per DeveloperCustom QuoteFree <$1M (Community)~$9K+/yrCustom Quote$499+Perpetual$999Perpetual · 1yr updatesFreeFreeCommunity MIT <$1M
Free Trial30 Days · Full Features No LimitsN/A (Free)30 DaysYes (Watermarked)Community <$1M RevYesCommunity (5 Pages)Free (10 Pages)N/A (Free)N/A (MIT Free <$1M)
Pricing TransparencyPublished & Clear Open SourceComplex AGPLMany TiersContact for QuoteNo Published PricingPublishedPublishedMIT; No RestrictionsMIT; 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.

Verified on IronPDF v2026.8.1 · .NET 10 · July 2026.

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 $999 with transparent team pricing that scales with your needs. Once you have a license, add it at the start of your application with IronPdf.License.LicenseKey = "KEY";.

View IronPDF Licensing

6. Troubleshooting & Technical Support

Having trouble with the following errors in HTML to PDF conversion? IronPDF engineers provide support 24/7; live chat via the widget on https://ironpdf.com/ is available 24/5.

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 the latest version (v2026.8.1) 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.

Common Issues and Troubleshooting

Images Don't Appear

Ensure that image URLs are accessible during rendering. If the images are stored locally, use absolute file paths or embed them directly in the HTML.

CSS Styles Are Missing

Verify that all CSS files are available and that the paths are correct. If possible, use absolute URLs for external stylesheets.

JavaScript Content Doesn't Render

If the page loads data asynchronously, configure the renderer to wait for JavaScript execution before generating the PDF.

External Fonts Are Missing

Make sure custom web fonts can be accessed during rendering. Alternatively, embed fonts directly into the HTML using @font-face.

HTML Looks Different in the PDF

Browsers and printed pages use different layouts. Each html element can render differently on paper than it does on screen, so consider creating a dedicated print stylesheet using @media print to optimize the output.

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

Next Steps
How to Merge or Split PDF DocumentsSee How-To
How to Add Custom Headers and Footers to PDF FilesSee How-To
How to Redact Text and Regions in PDFSee How-To

Frequently Asked Questions

How can I convert HTML to PDF in C#?

To convert HTML to PDF in C#, you can use the IronPDF library. Install it from NuGet and use the `ChromePdfRenderer.RenderHtmlAsPdf()` method to convert HTML strings, URLs, or files to PDFs with pixel-perfect accuracy.

What is the advantage of using IronPDF for HTML to PDF conversion?

IronPDF uses a robust Chrome-based engine to provide accurate HTML to PDF conversion with support for CSS3, HTML5, and JavaScript, ensuring a high-fidelity output that matches the web content perfectly.

Can IronPDF handle JavaScript in HTML to PDF conversion?

Yes, IronPDF fully supports JavaScript and AJAX during the HTML to PDF conversion process, which is particularly useful for rendering dynamic web pages and single-page applications.

What are some common use cases for converting HTML to PDF?

Common use cases include generating invoices, reports, certificates, and archiving web content like receipts, all while utilizing existing web design language and templates.

Does IronPDF support batch processing for generating multiple PDFs?

Yes, IronPDF supports batch processing, allowing you to generate multiple PDFs efficiently using HTML templates and libraries like Handlebars.NET for dynamic content rendering.

Can I create fillable PDF forms from HTML using IronPDF?

Yes, IronPDF allows you to convert HTML forms into fillable PDF fields by enabling the `CreatePdfFormsFromHtml` rendering option. This preserves HTML form elements as interactive fields in the PDF.

Is it possible to deploy IronPDF on cloud platforms like Azure or AWS?

IronPDF can be deployed on cloud platforms such as Azure and AWS, with specific configuration settings to ensure compatibility with headless rendering environments.

How do I secure PDFs generated with IronPDF?

IronPDF provides features to secure PDFs with password protection, permissions, and advanced encryption algorithms. You can also add digital signatures to ensure document authenticity.

What makes IronPDF different from other .NET PDF libraries?

IronPDF stands out due to its use of a Chromium rendering engine that provides high-fidelity conversion of modern web elements, including complete support for JavaScript and CSS3, making it suitable for enterprise-level applications.

How can I render only specific HTML elements to a PDF using IronPDF?

You can render specific HTML elements to PDF by isolating the target element in your HTML and using JavaScript rendering options or HTML parsing libraries to extract and render only the desired content.

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, and global government agencies.

...
Read More

Ready to Get Started?

Nuget Downloads 20,990,528Version:2026.9just released

Get your FREE

30-day Trial Key instantly.

bullet_checkedNo credit card or account creation required
bullet_testTest in production
without watermarks
bullet_calendar30 days fully
functional product
bullet_support24/5 technical
support during trial
Get your free 30-day Trial Key instantly.
No credit card or account creation required
C# NuGet Library for PDF
Install with NuGet

Version: 2026.9

PM > Install-Package IronPdf
nuget.org/packages/IronPdf/
  1. In Solution Explorer, right-click References, Manage NuGet Packages
  2. Select Browse and search "IronPdf"
  3. Select the package and install
C# PDF DLL
Download DLL

Version: 2026.9

or download Windows Installer here.

  1. Download and unzip IronPDF to a location such as ~/Libs within your Solution directory
  2. In Visual Studio Solution Explorer, right click References. Select Browse, "IronPdf.dll"

Licenses from $999

Key in blue circle

Get your free 30-day Trial Key instantly.

Your trial license will be sent to your email address

No limitations. 100% unlocked. No credit card.

OR
bullet_checkedNo credit card or account creation requiredNo limitations. 100% unlocked. No credit card.
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
Book your free Live Demo
Booking Badge

Trusted by Millions of Engineers Worldwide

Iron Software's customer logos
Get Your No-Obligation Consult
Complete the form below or email sales@ironsoftware.com
Your details will always be kept confidential.
Trusted by Millions of Engineers Worldwide
Iron Software's customer logos
Get your free 30-day Trial Key instantly.
No credit card or account creation required
C# NuGet Library for PDF
Install with NuGet

Version: 2026.9

PM > Install-Package IronPdf
nuget.org/packages/IronPdf/
  1. In Solution Explorer, right-click References, Manage NuGet Packages
  2. Select Browse and search "IronPdf"
  3. Select the package and install
C# PDF DLL
Download DLL

Version: 2026.9

or download Windows Installer here.

  1. Download and unzip IronPDF to a location such as ~/Libs within your Solution directory
  2. In Visual Studio Solution Explorer, right click References. Select Browse, "IronPdf.dll"

Licenses from $999