Skip to footer content
USING IRONPDF

Convert HTML to PDF in ASP.NET Core with C# -- IronPDF Guide

IronPDF converts HTML to PDF in ASP.NET using a Chrome-based rendering engine that transforms your HTML strings, files, or URLs into pixel-perfect PDF documents with just a few lines of C# code.

When your ASP.NET application needs to generate invoices, reports, or compliance documents on demand, the quality of the PDF output matters. End users expect formatted output that looks exactly like the original HTML -- complete with your CSS styling, custom fonts, and table layouts. The challenge is finding a library that handles this conversion without requiring complex workarounds for modern CSS or JavaScript-heavy content.

IronPDF is a C# PDF library built for this challenge. Its Chrome-based rendering engine processes HTML the same way a real browser does, which means your CSS3 properties, media queries, and JavaScript-rendered content all appear correctly in the final document. The sections below walk through installation, the three core rendering methods, form data handling, advanced formatting features, and authentication support -- everything needed to integrate production-ready PDF generation into your ASP.NET Core application.

How Do You Quickly Convert HTML to PDF in ASP.NET Core?

Getting started with HTML to PDF conversion in ASP.NET Core requires just a few lines of code. First, install IronPDF via the NuGet Package Manager:

Install-Package IronPdf

Once installed, the ChromePdfRenderer class is the main entry point for all rendering operations. Here is a complete example showing how to convert an HTML string to a downloadable PDF inside an ASP.NET Core MVC controller:

  1. Install IronPDF with NuGet Package Manager

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

    using IronPdf;
    using Microsoft.AspNetCore.Mvc;
    
    // program.cs
    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddControllersWithViews();
    var app = builder.Build();
    app.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    app.Run();
    
    // PdfController.cs
    public class PdfController : Controller
    {
        public IActionResult GeneratePdf()
        {
            var renderer = new ChromePdfRenderer();
            string html = @"
                <h1>Invoice #2024-001</h1>
                <p>Generated on: " + DateTime.Now.ToString("yyyy-MM-dd") + @"</p>
                <table>
                    <tr><th>Item</th><th>Price</th></tr>
                    <tr><td>Professional License</td><td>$799</td></tr>
                </table>";
            var pdf = renderer.RenderHtmlAsPdf(html);
            return File(pdf.BinaryData, "application/pdf", "invoice.pdf");
        }
    }
  3. Deploy to test on your live environment

    Start using IronPDF in your project today with a free trial

    arrow pointer

What Does the Generated PDF Look Like?

PDF viewer displaying a simple invoice document with number #2024-001, showing an invoice header, generation date, and a table with Item and Price columns containing a Professional License entry for $799

The ChromePdfRenderer class handles all the complex rendering, ensuring your HTML structure, CSS styles, and even JavaScript render correctly in the final PDF output. The return value is a PdfDocument object whose BinaryData property you can stream directly to the browser as a file download.

How Do You Choose the Right Rendering Method for Your Source?

IronPDF provides three primary rendering methods, each designed for a specific content source. Understanding which method fits your scenario avoids unnecessary complexity and keeps your controller code clean.

IronPDF rendering methods by content source
Source Type Method Best For
HTML string in memory RenderHtmlAsPdf Database-driven reports, templated invoices, dynamic content
HTML file on disk RenderHtmlFileAsPdf Static templates in wwwroot, design-agency-supplied layouts
Live web URL RenderUrlAsPdf Archiving pages, capturing SPAs after JavaScript renders

How Do You Convert Dynamic HTML Strings?

When working with dynamic content like database-driven reports, use RenderHtmlAsPdf to convert HTML strings directly. This method accepts any valid HTML markup and returns a fully rendered PDF:

var renderer = new ChromePdfRenderer();
string htmlContent = BuildDynamicHtml(); // your method to generate HTML
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
pdf.SaveAs("dynamic-report.pdf");
var renderer = new ChromePdfRenderer();
string htmlContent = BuildDynamicHtml(); // your method to generate HTML
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
pdf.SaveAs("dynamic-report.pdf");
Dim renderer As New ChromePdfRenderer()
Dim htmlContent As String = BuildDynamicHtml() ' your method to generate HTML
Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)
pdf.SaveAs("dynamic-report.pdf")
$vbLabelText   $csharpLabel

IronPDF test report displaying rendered HTML content with CSS styling including a blue header reading 'IronPDF Test Report', green styled paragraph text, and a formatted data table containing product information with items like widgets and tools

This approach works well for generating PDF documents from HTML templates populated with real-time data, form submissions, or any dynamically generated content. The rendering engine preserves all CSS styling including custom fonts, colors, and table formatting. When your HTML references external stylesheets or images using relative paths, pass a baseUrl as the second argument so the renderer can resolve those assets correctly.

How Do You Convert Static HTML Files from Disk?

For HTML templates stored as physical files, use RenderHtmlFileAsPdf to convert them without loading them into memory first. This is efficient for large templates and avoids string concatenation:

var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlFileAsPdf("wwwroot/templates/report-template.html");
pdf.SaveAs("report.pdf");
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlFileAsPdf("wwwroot/templates/report-template.html");
pdf.SaveAs("report.pdf");
Dim renderer As New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlFileAsPdf("wwwroot/templates/report-template.html")
pdf.SaveAs("report.pdf")
$vbLabelText   $csharpLabel

This method automatically resolves relative paths for CSS stylesheets, images, and other external resources referenced in the file. It works well when your design team maintains separate HTML template files outside the application's C# codebase. The method supports CSS print media queries and custom fonts, so templates built for print environments render faithfully without extra configuration.

How Do You Convert a Web Page URL to PDF?

To capture a live web page or render a URL-accessible page as a PDF, use RenderUrlAsPdf. This method launches the Chrome engine, navigates to the URL, waits for the page to fully load, and then captures the rendered output:

var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.EnableJavaScript = true;
renderer.RenderingOptions.WaitFor.RenderDelay(1000);
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Screen;
var pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/PDF");
pdf.SaveAs("webpage.pdf");
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.EnableJavaScript = true;
renderer.RenderingOptions.WaitFor.RenderDelay(1000);
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Screen;
var pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/PDF");
pdf.SaveAs("webpage.pdf");
Dim renderer = New ChromePdfRenderer()
renderer.RenderingOptions.EnableJavaScript = True
renderer.RenderingOptions.WaitFor.RenderDelay(1000)
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Screen
Dim pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/PDF")
pdf.SaveAs("webpage.pdf")
$vbLabelText   $csharpLabel

Wikipedia main page displayed in a PDF viewer showing the complete webpage layout with navigation, content sections, featured article preview, and Wikipedia logo, demonstrating successful HTML to PDF conversion with preserved formatting and images

The WaitFor.RenderDelay option tells the renderer to pause after page load before capturing. This is valuable for single-page applications that build their DOM through JavaScript after the initial HTML response arrives. Setting EnableJavaScript = true activates the full Chrome JavaScript engine, so charts, data grids, and other JavaScript-rendered components appear in the PDF just as they do in a browser.

How Do You Handle Form Data and POST Requests?

Processing form data before PDF generation is a common pattern in ASP.NET applications -- order confirmations, delivery slips, and receipts all follow this model. The approach is to bind the posted form data to a model, build an HTML string from that model, and then render the string as a PDF:

[HttpPost]
public IActionResult ProcessFormToPdf(OrderModel model)
{
    var renderer = new ChromePdfRenderer();
    string html = $@"
        <h2>Order Confirmation</h2>
        <p>Customer: {model.CustomerName}</p>
        <p>Order Date: {model.OrderDate:yyyy-MM-dd}</p>
        <ul>
            {string.Join("", model.Items.Select(i => $"<li>{i.Name} -- ${i.Price}</li>"))}
        </ul>
        <p><strong>Total: ${model.Total}</strong></p>";
    var pdf = renderer.RenderHtmlAsPdf(html);
    string fileName = $"order-{model.OrderId}.pdf";
    return File(pdf.BinaryData, "application/pdf", fileName);
}
[HttpPost]
public IActionResult ProcessFormToPdf(OrderModel model)
{
    var renderer = new ChromePdfRenderer();
    string html = $@"
        <h2>Order Confirmation</h2>
        <p>Customer: {model.CustomerName}</p>
        <p>Order Date: {model.OrderDate:yyyy-MM-dd}</p>
        <ul>
            {string.Join("", model.Items.Select(i => $"<li>{i.Name} -- ${i.Price}</li>"))}
        </ul>
        <p><strong>Total: ${model.Total}</strong></p>";
    var pdf = renderer.RenderHtmlAsPdf(html);
    string fileName = $"order-{model.OrderId}.pdf";
    return File(pdf.BinaryData, "application/pdf", fileName);
}
Imports System
Imports System.Linq
Imports Microsoft.AspNetCore.Mvc

<HttpPost>
Public Function ProcessFormToPdf(model As OrderModel) As IActionResult
    Dim renderer = New ChromePdfRenderer()
    Dim html As String = $"
        <h2>Order Confirmation</h2>
        <p>Customer: {model.CustomerName}</p>
        <p>Order Date: {model.OrderDate:yyyy-MM-dd}</p>
        <ul>
            {String.Join("", model.Items.Select(Function(i) $"<li>{i.Name} -- ${i.Price}</li>"))}
        </ul>
        <p><strong>Total: ${model.Total}</strong></p>"
    Dim pdf = renderer.RenderHtmlAsPdf(html)
    Dim fileName As String = $"order-{model.OrderId}.pdf"
    Return File(pdf.BinaryData, "application/pdf", fileName)
End Function
$vbLabelText   $csharpLabel

What Does the Form Interface Look Like?

Web form interface showing an order creation page with customer details section containing name field 'Jane Doe' and date '19/11/2025', order items section displaying 'Laptop' priced at '1300', order summary showing total, and a blue 'Generate PDF' button

How Does Form Data Appear in the Generated PDF?

PDF viewer showing a clean order confirmation document with header 'Order Confirmation', customer name 'Jane Doe', order date '2025-11-19', itemized list showing laptop purchase for $1300, demonstrating successful form-to-PDF conversion

For more advanced document scenarios, you can integrate PDF forms or edit existing PDF templates with pre-filled fields. The library also supports digital signatures for legal documents and contracts, letting you add cryptographically verifiable signatures to any generated document.

One important consideration when embedding user data into HTML strings is sanitization. Always escape user-supplied strings before inserting them into HTML to prevent injection issues. A simple System.Web.HttpUtility.HtmlEncode(model.CustomerName) call on each field keeps the template safe before passing it to the renderer.

How Do You Add Professional Formatting, Headers, and Watermarks?

How Do You Configure Headers, Footers, and Watermarks?

Professional PDF documents often require headers and footers on every page, along with watermarks for draft or confidential documents. IronPDF handles both through properties on the RenderingOptions object and the ApplyWatermark method on the resulting PdfDocument:

var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
    MaxHeight = 25,
    HtmlFragment = "<div style='text-align:center'>Annual Report 2024</div>"
};
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter
{
    MaxHeight = 20,
    HtmlFragment = "<div style='text-align:center'>Page {page} of {total-pages}</div>"
};
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
pdf.ApplyWatermark("<h2 style='color:red;opacity:0.3'>CONFIDENTIAL</h2>",
    30, VerticalAlignment.Middle, HorizontalAlignment.Center);
pdf.SaveAs("report-with-watermark.pdf");
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
    MaxHeight = 25,
    HtmlFragment = "<div style='text-align:center'>Annual Report 2024</div>"
};
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter
{
    MaxHeight = 20,
    HtmlFragment = "<div style='text-align:center'>Page {page} of {total-pages}</div>"
};
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
pdf.ApplyWatermark("<h2 style='color:red;opacity:0.3'>CONFIDENTIAL</h2>",
    30, VerticalAlignment.Middle, HorizontalAlignment.Center);
pdf.SaveAs("report-with-watermark.pdf");
Imports IronPdf

Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter With {
    .MaxHeight = 25,
    .HtmlFragment = "<div style='text-align:center'>Annual Report 2024</div>"
}
renderer.RenderingOptions.HtmlFooter = New HtmlHeaderFooter With {
    .MaxHeight = 20,
    .HtmlFragment = "<div style='text-align:center'>Page {page} of {total-pages}</div>"
}
Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)
pdf.ApplyWatermark("<h2 style='color:red;opacity:0.3'>CONFIDENTIAL</h2>", 30, VerticalAlignment.Middle, HorizontalAlignment.Center)
pdf.SaveAs("report-with-watermark.pdf")
$vbLabelText   $csharpLabel

IronPDF test report showing a PDF document with custom blue heading 'IronPDF Test Report', green inline text formatting, a data table with product information, and a red 'CONFIDENTIAL' watermark positioned diagonally across the page

The {page} and {total-pages} placeholders in footer HTML are automatically replaced at render time, so you get correct page numbers without any post-processing. You can also add page numbers, background images or foreground overlays, and custom text or image stamps.

How Do You Use CSS Print Media for PDF Layout Control?

To ensure your PDF output matches expectations, use CSS @media print rules and the PdfCssMediaType.Print setting. IronPDF fully supports page break control and custom paper sizes:

var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;
renderer.RenderingOptions.ViewPortWidth = 1024;
renderer.RenderingOptions.MarginTop = 10;
renderer.RenderingOptions.MarginBottom = 10;
renderer.RenderingOptions.MarginLeft = 10;
renderer.RenderingOptions.MarginRight = 10;
string html = @"
    <style>
        @media print {
            .no-print { display: none; }
            body { font-size: 12pt; }
            .page-break { page-break-after: always; }
        }
        @page {
            size: A4;
            margin: 1cm;
        }
    </style>
    <div class='content'>
        <h1>Professional Report</h1>
        <div class='page-break'></div>
        <h2>Section 2</h2>
    </div>";
var pdf = renderer.RenderHtmlAsPdf(html);
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;
renderer.RenderingOptions.ViewPortWidth = 1024;
renderer.RenderingOptions.MarginTop = 10;
renderer.RenderingOptions.MarginBottom = 10;
renderer.RenderingOptions.MarginLeft = 10;
renderer.RenderingOptions.MarginRight = 10;
string html = @"
    <style>
        @media print {
            .no-print { display: none; }
            body { font-size: 12pt; }
            .page-break { page-break-after: always; }
        }
        @page {
            size: A4;
            margin: 1cm;
        }
    </style>
    <div class='content'>
        <h1>Professional Report</h1>
        <div class='page-break'></div>
        <h2>Section 2</h2>
    </div>";
var pdf = renderer.RenderHtmlAsPdf(html);
Imports IronPdf

Dim renderer As New ChromePdfRenderer()
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print
renderer.RenderingOptions.ViewPortWidth = 1024
renderer.RenderingOptions.MarginTop = 10
renderer.RenderingOptions.MarginBottom = 10
renderer.RenderingOptions.MarginLeft = 10
renderer.RenderingOptions.MarginRight = 10

Dim html As String = "
    <style>
        @media print {
            .no-print { display: none; }
            body { font-size: 12pt; }
            .page-break { page-break-after: always; }
        }
        @page {
            size: A4;
            margin: 1cm;
        }
    </style>
    <div class='content'>
        <h1>Professional Report</h1>
        <div class='page-break'></div>
        <h2>Section 2</h2>
    </div>"

Dim pdf = renderer.RenderHtmlAsPdf(html)
$vbLabelText   $csharpLabel

PDF document viewer displaying a two-page professional report at 76% zoom with 'Professional Report' title on page 1 and 'Section 2' heading on page 2, showing clean layout with proper page breaks and CSS formatting applied

Using print CSS ensures your PDF documents maintain professional formatting while hiding unnecessary web elements like navigation menus or interactive buttons. Setting CssMediaType = PdfCssMediaType.Print tells the renderer to apply your @media print rules rather than the screen styles, which typically removes background decorations and adjusts typography for print output. You can also configure custom margins per page and control page orientation and rotation for wide-format or rotated reports.

The W3C CSS Paged Media specification defines how properties like @page, page-break-before, and widows should behave in paged output. IronPDF's Chrome engine follows this specification closely, so styles written to the CSS standard translate accurately into the PDF without manual adjustments.

How Do You Handle Authentication for Protected Pages?

For secure applications, IronPDF supports various authentication methods including cookies, HTTP request headers, and network credentials. This lets you render pages that require a logged-in session or basic authentication:

var renderer = new ChromePdfRenderer();
renderer.RequestContext.Cookies.Add(new Cookie
{
    Name = "SessionId",
    Value = "your-session-token",
    Domain = "example.com"
});
renderer.ChromePdfRenderOptions.HttpLoginCredentials = new HttpLoginCredentials
{
    Username = "user",
    Password = "password"
};
var pdf = renderer.RenderUrlAsPdf("https://app.example.com/protected/report");
var renderer = new ChromePdfRenderer();
renderer.RequestContext.Cookies.Add(new Cookie
{
    Name = "SessionId",
    Value = "your-session-token",
    Domain = "example.com"
});
renderer.ChromePdfRenderOptions.HttpLoginCredentials = new HttpLoginCredentials
{
    Username = "user",
    Password = "password"
};
var pdf = renderer.RenderUrlAsPdf("https://app.example.com/protected/report");
Dim renderer = New ChromePdfRenderer()
renderer.RequestContext.Cookies.Add(New Cookie With {
    .Name = "SessionId",
    .Value = "your-session-token",
    .Domain = "example.com"
})
renderer.ChromePdfRenderOptions.HttpLoginCredentials = New HttpLoginCredentials With {
    .Username = "user",
    .Password = "password"
}
Dim pdf = renderer.RenderUrlAsPdf("https://app.example.com/protected/report")
$vbLabelText   $csharpLabel

You can also encrypt the resulting PDF with an owner password and user password, restricting actions like printing, copying, or editing. Combining authentication-based rendering with PDF-level permissions gives you control over both who can generate a document and what recipients can do with it once they have it.

For enterprise environments, consider using the async rendering API when generating PDFs inside web request handlers. Async rendering keeps the ASP.NET thread pool free while the Chrome engine processes the document, which improves throughput under concurrent load. The library also supports multi-threaded rendering for batch document generation scenarios.

Why Does the Chrome Rendering Engine Matter for HTML to PDF?

Most PDF generation libraries work by parsing HTML themselves using a custom engine. This means they support only a subset of CSS properties, lack JavaScript execution, and struggle with modern layout techniques like CSS Grid or Flexbox. IronPDF takes a different approach by embedding the Chrome engine -- the same technology that powers the Google Chrome browser.

The practical result is that any HTML page that displays correctly in Chrome will render correctly as a PDF through IronPDF. This eliminates a common class of bugs where the PDF output diverges from the expected appearance because the rendering engine interprets CSS differently from the browser the developer used during design.

The MDN Web Docs reference for CSS Paged Media and Microsoft's ASP.NET Core documentation both describe features that IronPDF supports through its Chrome-based foundation. Developers already familiar with standard HTML, CSS, and JavaScript can apply that knowledge directly to PDF generation without learning a separate document layout language.

IronPDF's RenderingOptions expose controls for paper size, margins, JavaScript execution, and rendering delays. The library handles UTF-8 text and international character sets, web fonts referenced via Google Fonts or local files, and can even convert Markdown documents to PDF. For archival or accessibility compliance requirements, it supports PDF/A and PDF/UA output formats. The library runs on Windows, Linux, and macOS and deploys to Azure and AWS without additional configuration.

What Are Your Next Steps?

Converting HTML to PDF in ASP.NET C# with IronPDF gives your application a reliable, browser-accurate document generation pipeline. The three rendering methods -- HTML string, HTML file, and URL -- cover the full range of content sources you will encounter in practice. Advanced features like headers, footers, watermarks, and print CSS let you produce professional output without post-processing the PDF manually.

The next step is to install the NuGet package and run the quickstart example from the first section of this guide. From there, explore the complete C# PDF tutorial for deeper coverage of document structure, or review the PDF editing guide to learn how to merge, split, annotate, and extract content from existing PDFs.

If your project targets Blazor, the Blazor PDF tutorial walks through server-side and WebAssembly integration. For MVC projects, the MVC Core PDF guide and Razor Pages guide cover template-based rendering with .cshtml views. For debugging and performance tuning, IronPDF provides custom logging and performance guidance that help identify bottlenecks in high-volume document generation workflows.

Start a free trial to test every feature of the library in your own project before committing to a license. For production deployments, licensing options are available for individual developers, teams, and enterprise redistribution scenarios.

Frequently Asked Questions

How can I convert HTML to PDF in ASP.NET Core?

Install IronPDF via NuGet, create a ChromePdfRenderer instance, and call RenderHtmlAsPdf with your HTML string. The renderer returns a PdfDocument whose BinaryData you can stream to the browser.

What makes IronPDF suitable for HTML to PDF conversion?

IronPDF embeds the Chrome rendering engine, so any HTML page that displays correctly in Chrome renders correctly as a PDF. This includes CSS3, JavaScript-rendered content, web fonts, and responsive layouts.

Is it possible to generate invoices and reports using IronPDF in ASP.NET?

Yes. Build an HTML string from your data model, pass it to RenderHtmlAsPdf, and return the BinaryData as a file download. IronPDF preserves table formatting, custom fonts, and CSS styling in the output.

Does IronPDF support CSS print media queries?

Yes. Set RenderingOptions.CssMediaType = PdfCssMediaType.Print to activate @media print rules, which hide navigation elements and apply print-optimized typography.

Can IronPDF handle JavaScript-rendered content?

Yes. Set RenderingOptions.EnableJavaScript = true and use WaitFor.RenderDelay to pause after page load, giving the JavaScript engine time to build the DOM before the PDF is captured.

How does IronPDF handle authentication for protected pages?

IronPDF supports session cookies, HTTP headers, and basic authentication credentials through the RequestContext.Cookies and ChromePdfRenderOptions.HttpLoginCredentials properties.

What platforms does IronPDF support?

IronPDF runs on Windows, Linux, and macOS and can be deployed to Azure and AWS. It targets .NET 6, .NET 7, .NET 8, and .NET Framework 4.6.2 and above.

Does IronPDF support PDF/A output for archival?

Yes. IronPDF supports PDF/A compliance for long-term archival and PDF/UA for accessibility. These output modes can be configured through the SaveAsPdfA and SaveAsPdfUA methods.

Curtis Chau
Technical Writer

Curtis Chau holds a Bachelor’s degree in Computer Science (Carleton University) and specializes in front-end development with expertise in Node.js, TypeScript, JavaScript, and React. Passionate about crafting intuitive and aesthetically pleasing user interfaces, Curtis enjoys working with modern frameworks and creating well-structured, visually appealing manuals.

...

Read More

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me