Skip to footer content
USING IRONPDF

How to Convert HTML to PDF in ASP.NET Core

How Can Developers Convert HTML to PDF in ASP.NET Core?

IronPDF makes it straightforward to convert HTML to PDF in ASP.NET Core by using Chrome's rendering engine, so you can transform dynamic web content, reports, and invoices into precise PDFs with just a few lines of code -- preserving all CSS styles and JavaScript functionality.

Struggling to get crisp, pixel-perfect reports and invoices out of your ASP.NET Core app? You're not alone.

Every developer eventually needs to convert dynamic web content -- like reports or order confirmations -- into a reliable, downloadable PDF. This is a fundamental requirement for generating everything from invoices and detailed reports to secure, archivable document formats. The challenge lies in getting complex HTML, with all its CSS and JavaScript, to render perfectly as a PDF output.

That's where IronPDF steps in. It uses Chrome's rendering engine under the hood, so whatever you see in a browser is exactly what you get in the PDF output. Whether you're working with ASPX pages, modern Razor views, or raw HTML strings, the conversion process is consistent and predictable.

This guide walks you through the most common ASP.NET Core HTML to PDF scenarios -- URL to PDF conversion, HTML string rendering, and HTML file processing -- with working C# code examples for each approach.

Start your free trial and begin converting HTML to PDF documents today.

Get stated with IronPDF now.
green arrow pointer

How Do You Add the PDF Library to an ASP.NET Core Project?

Installing IronPDF takes a single command in the NuGet Package Manager Console or via the .NET CLI. IronPDF is available as a NuGet package and targets .NET 6, 7, 8, and 10:

Install-Package IronPdf
dotnet add package IronPdf
Install-Package IronPdf
dotnet add package IronPdf
SHELL

Once installed, IronPDF provides complete HTML rendering capabilities, supporting modern HTML elements, CSS styles, and JavaScript execution. The library handles complex HTML structures and CSS properties reliably, including Bootstrap and Flex layouts.

IronPDF supports deployment across a wide range of environments:

IronPDF Supported Deployment Environments
Environment Support Level Notes
Windows Full IIS and self-hosted, all versions
Linux Full Ubuntu, Debian, CentOS, Alpine
macOS Full Arm and x64 architectures
Azure Full App Service, Functions, Containers
AWS Lambda Full Serverless PDF generation
Docker Full Includes remote IronPDF Engine option

After installation, the ChromePdfRenderer class is your main entry point. It exposes a RenderingOptions property where you control paper size, margins, headers, JavaScript execution, and much more. The sections below cover the three main conversion approaches you'll use in a typical ASP.NET Core application.

How Do You Convert an HTML String to a PDF Document?

Converting an HTML string directly to a PDF file is the most direct approach and requires no file system access. This makes it ideal for generating PDFs from dynamically assembled HTML -- such as order confirmations, invoices, or report templates populated from a database.

The following code shows a complete ASP.NET Core controller action that converts an HTML string to a PDF using IronPDF:

using Microsoft.AspNetCore.Mvc;
using IronPdf;

namespace HtmlToPdf.Controllers
{
    public class PdfController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public IActionResult ConvertHtmlStringToPdf()
        {
            string htmlContent = @"
<html>
  <head>
    <title>IronPDF Test</title>
    <style>
      body { font-family: Arial; margin: 40px; }
      h1 { color: #2b5797; }
      table { border-collapse: collapse; width: 100%; margin-top: 20px; }
      th, td { border: 1px solid #ccc; padding: 8px; }
      th { background: #f0f0f0; }
    </style>
  </head>
  <body>
    <h1>IronPDF HTML to PDF Test</h1>
    <p>This is a simple test of converting an HTML string to PDF using IronPDF.</p>
    <table>
      <tr><th>Item</th><th>Price</th></tr>
      <tr><td>Apples</td><td>$1.50</td></tr>
      <tr><td>Bananas</td><td>$0.90</td></tr>
    </table>
    <p><em>End of test document.</em></p>
  </body>
</html>";
            // Initialize the PDF converter
            var renderer = new ChromePdfRenderer();
            // Configure page size and margins
            renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
            renderer.RenderingOptions.MarginTop = 20;
            renderer.RenderingOptions.MarginBottom = 20;
            // Convert the HTML string to a PDF document
            var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
            // Return the PDF file as a download
            return File(pdfDocument.BinaryData, "application/pdf", "output.pdf");
        }
    }
}
using Microsoft.AspNetCore.Mvc;
using IronPdf;

namespace HtmlToPdf.Controllers
{
    public class PdfController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public IActionResult ConvertHtmlStringToPdf()
        {
            string htmlContent = @"
<html>
  <head>
    <title>IronPDF Test</title>
    <style>
      body { font-family: Arial; margin: 40px; }
      h1 { color: #2b5797; }
      table { border-collapse: collapse; width: 100%; margin-top: 20px; }
      th, td { border: 1px solid #ccc; padding: 8px; }
      th { background: #f0f0f0; }
    </style>
  </head>
  <body>
    <h1>IronPDF HTML to PDF Test</h1>
    <p>This is a simple test of converting an HTML string to PDF using IronPDF.</p>
    <table>
      <tr><th>Item</th><th>Price</th></tr>
      <tr><td>Apples</td><td>$1.50</td></tr>
      <tr><td>Bananas</td><td>$0.90</td></tr>
    </table>
    <p><em>End of test document.</em></p>
  </body>
</html>";
            // Initialize the PDF converter
            var renderer = new ChromePdfRenderer();
            // Configure page size and margins
            renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
            renderer.RenderingOptions.MarginTop = 20;
            renderer.RenderingOptions.MarginBottom = 20;
            // Convert the HTML string to a PDF document
            var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
            // Return the PDF file as a download
            return File(pdfDocument.BinaryData, "application/pdf", "output.pdf");
        }
    }
}
$vbLabelText   $csharpLabel

What Does the Generated PDF Look Like?

PDF viewer displaying a test document created with IronPDF, showing a simple table with items (Apples $1.50, Bananas $0.90) demonstrating HTML to PDF conversion

The ChromePdfRenderer class handles the entire conversion pipeline, transforming your HTML string into a properly formatted, multi-page PDF. The resulting document preserves all styling -- inline CSS, embedded stylesheets, and even font rules -- exactly as defined in the source HTML. This pattern is particularly effective for generating invoices, statements, and any document whose layout you control end-to-end through code.

You can extend this pattern to add headers and footers or custom watermarks to every page. IronPDF also supports PDF compression to reduce file sizes without losing visual quality.

How Do You Convert HTML Files to PDF Files?

When working with existing HTML template files stored on the server, IronPDF can read and convert them while preserving all linked resources such as external stylesheets, local images, and JavaScript files. This approach works well for template-based document generation pipelines where designers maintain HTML files independently from the application code:

using IronPdf;
using Microsoft.AspNetCore.Mvc;
using System.IO;

namespace YourApp.Controllers
{
    public class DocumentController : Controller
    {
        private readonly IWebHostEnvironment _environment;

        public DocumentController(IWebHostEnvironment environment)
        {
            _environment = environment;
        }

        [HttpGet]
        public IActionResult GeneratePdfFromTemplate(string templateName)
        {
            // Resolve the full path to the HTML template
            string htmlFilePath = Path.Combine(_environment.WebRootPath, "templates", $"{templateName}.html");
            var renderer = new ChromePdfRenderer();
            // Use print media type for print-optimized CSS rules
            renderer.RenderingOptions.EnableJavaScript = true;
            renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;
            // Add a header to every generated page
            renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
            {
                Height = 25,
                HtmlFragment = "<div style='text-align:center'>Company Report</div>"
            };
            // Convert the HTML file to a PDF document
            var pdf = renderer.RenderHtmlFileAsPdf(htmlFilePath);
            return File(pdf.BinaryData, "application/pdf", $"{templateName}_generated.pdf");
        }
    }
}
using IronPdf;
using Microsoft.AspNetCore.Mvc;
using System.IO;

namespace YourApp.Controllers
{
    public class DocumentController : Controller
    {
        private readonly IWebHostEnvironment _environment;

        public DocumentController(IWebHostEnvironment environment)
        {
            _environment = environment;
        }

        [HttpGet]
        public IActionResult GeneratePdfFromTemplate(string templateName)
        {
            // Resolve the full path to the HTML template
            string htmlFilePath = Path.Combine(_environment.WebRootPath, "templates", $"{templateName}.html");
            var renderer = new ChromePdfRenderer();
            // Use print media type for print-optimized CSS rules
            renderer.RenderingOptions.EnableJavaScript = true;
            renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;
            // Add a header to every generated page
            renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
            {
                Height = 25,
                HtmlFragment = "<div style='text-align:center'>Company Report</div>"
            };
            // Convert the HTML file to a PDF document
            var pdf = renderer.RenderHtmlFileAsPdf(htmlFilePath);
            return File(pdf.BinaryData, "application/pdf", $"{templateName}_generated.pdf");
        }
    }
}
$vbLabelText   $csharpLabel

How Does the Template Conversion Result Appear?

PDF viewer displaying a Monthly Sales Report generated from HTML, showing a table with product sales data for IronPDF, IronOCR, and IronXL licenses

This approach reads HTML documents from disk and converts them while maintaining the complete document structure. All CSS properties, image references, and complex HTML elements such as tables and nested containers are preserved in the output. IronPDF resolves relative resource paths against the source file's location, so linked stylesheets and images load without any extra configuration.

IronPDF also supports CSS print media queries correctly, which means you can define print-specific rules in your HTML templates -- hiding navigation bars, adjusting font sizes, or enabling page-break hints -- and they will apply only during PDF generation, not when the page loads in a browser.

How Do You Convert Pages That Require Authentication?

ASP.NET Core applications often protect content behind forms authentication. When converting pages that require a valid session, IronPDF can pass authentication cookies along with the HTTP request so the rendered page reflects what an authenticated user would see:

[Authorize]
public IActionResult ConvertAuthenticatedPage()
{
    var renderer = new ChromePdfRenderer();
    // Build the URL for the protected resource
    string currentUrl = $"{Request.Scheme}://{Request.Host}/SecureContent";
    // Forward the authentication cookie to IronPDF
    var authCookie = Request.Cookies[".AspNetCore.Cookies"];
    if (!string.IsNullOrEmpty(authCookie))
    {
        renderer.RenderingOptions.CustomCookies = new System.Collections.Generic.Dictionary<string, string>
        {
            { ".AspNetCore.Cookies", authCookie }
        };
    }
    // Convert the authenticated page to a PDF file
    var pdf = renderer.RenderUrlAsPdf(currentUrl);
    return File(pdf.BinaryData, "application/pdf", "secure_document.pdf");
}
[Authorize]
public IActionResult ConvertAuthenticatedPage()
{
    var renderer = new ChromePdfRenderer();
    // Build the URL for the protected resource
    string currentUrl = $"{Request.Scheme}://{Request.Host}/SecureContent";
    // Forward the authentication cookie to IronPDF
    var authCookie = Request.Cookies[".AspNetCore.Cookies"];
    if (!string.IsNullOrEmpty(authCookie))
    {
        renderer.RenderingOptions.CustomCookies = new System.Collections.Generic.Dictionary<string, string>
        {
            { ".AspNetCore.Cookies", authCookie }
        };
    }
    // Convert the authenticated page to a PDF file
    var pdf = renderer.RenderUrlAsPdf(currentUrl);
    return File(pdf.BinaryData, "application/pdf", "secure_document.pdf");
}
$vbLabelText   $csharpLabel

This technique captures the full rendered output of pages that sit behind a login wall. When the target URL belongs to the same application, all relative resource paths resolve correctly because the renderer inherits the same base URL context. You can also configure custom HTTP request headers for API key authentication or other header-based security schemes.

For stronger document security after generation, consider applying PDF passwords and permissions or digitally signing your PDFs to prevent unauthorized modification. IronPDF also supports PDF/A compliance for long-term archiving and PDF/UA format for accessibility requirements, which can be important for regulated industries.

What About Converting ASPX Files and Dynamic JavaScript Content?

For legacy ASPX page conversion or documents that depend on JavaScript to populate content at runtime, IronPDF handles the rendering process reliably. You can configure a render delay to let JavaScript finish executing before the page is captured:

public IActionResult ConvertDynamicContent()
{
    var renderer = new ChromePdfRenderer();
    // Enable JavaScript so dynamic content renders correctly
    renderer.RenderingOptions.EnableJavaScript = true;
    // Wait 1 second after page load for JavaScript to complete
    renderer.RenderingOptions.WaitFor.RenderDelay(1000);
    // Generate your dynamic HTML string
    string dynamicHtml = GenerateDynamicHtml();
    var pdf = renderer.RenderHtmlAsPdf(dynamicHtml);
    return File(pdf.BinaryData, "application/pdf", "dynamic.pdf");
}
public IActionResult ConvertDynamicContent()
{
    var renderer = new ChromePdfRenderer();
    // Enable JavaScript so dynamic content renders correctly
    renderer.RenderingOptions.EnableJavaScript = true;
    // Wait 1 second after page load for JavaScript to complete
    renderer.RenderingOptions.WaitFor.RenderDelay(1000);
    // Generate your dynamic HTML string
    string dynamicHtml = GenerateDynamicHtml();
    var pdf = renderer.RenderHtmlAsPdf(dynamicHtml);
    return File(pdf.BinaryData, "application/pdf", "dynamic.pdf");
}
$vbLabelText   $csharpLabel

What Does Dynamic Content Look Like When Converted?

PDF viewer displaying a test document generated by IronPDF showing dynamic content with JavaScript-set timestamp of 4:14:10 PM

A common pain point in HTML to PDF conversion is unwanted page breaks that split headings from their content or cut table rows mid-row. IronPDF addresses this through configurable page break control using standard CSS page-break-before and page-break-inside rules alongside IronPDF's WaitFor API. The library also supports async PDF generation for improved throughput in high-traffic scenarios.

For advanced JavaScript applications -- such as charts rendered by D3.js or React components -- you can inject and execute custom JavaScript before the render snapshot is taken, ensuring the chart or component has fully mounted before the PDF is generated.

How Do You Handle CSS Styles and Advanced HTML Rendering?

IronPDF's rendering engine supports advanced CSS and HTML5 features through its complete rendering options API. When converting HTML to PDF, the library interprets CSS properties correctly -- including complex layouts built with Flexbox, CSS Grid, and responsive media queries. The PDF output maintains the visual fidelity of the source page, including external stylesheets, inline styles, and JavaScript-rendered content that mutates the DOM before the page is captured.

The conversion process handles multi-page documents, blank page suppression, and automatic page size adjustment without manual configuration. It also manages specialized scenarios such as applying different headers or footers on specific pages, or gracefully handling content that extends across dozens of pages in a report.

Additional rendering capabilities worth knowing about:

  • International text: Full support for UTF-8 encoding and international languages, including right-to-left scripts such as Arabic and Hebrew
  • Vector graphics: Native SVG rendering without rasterization, so graphics remain sharp at any zoom level
  • Document structure: Table of contents generation, bookmark support, and PDF metadata editing for author, title, and keyword fields
  • Post-processing: Merge or split PDFs, extract text and images, and create fillable forms programmatically

These capabilities make IronPDF a practical choice for document-heavy applications where the output quality of a basic converter falls short of production requirements. For teams that are new to PDF generation in .NET, Microsoft's ASP.NET Core documentation provides good background on controller actions and middleware, which is useful context when integrating any PDF library into a web application.

Why Is This the Right PDF Library for Your .NET Project?

IronPDF is a production-ready .NET library for HTML to PDF conversion, offering reliable performance compared to alternatives like Aspose, iText, and Syncfusion. Unlike basic PDF converters, it provides full support for modern web standards -- handling everything from simple HTML strings to complex web applications with JavaScript-rendered content and forms authentication.

The library works equally well for Blazor applications and MAUI projects, and can be used with F# in addition to C#. For enterprise environments, IronPDF supports IIS hosting, Azure Functions, and Docker containers.

IronPDF is free to try during development. Download IronPDF today and start converting HTML content into professional PDF documents. Explore the complete documentation, code examples, and API reference to take full advantage of HTML to PDF conversion in your ASP.NET Core applications.

Frequently Asked Questions

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

Developers can convert HTML to PDF in ASP.NET Core by using IronPDF, which provides a straightforward API for rendering HTML content into a PDF document. This includes converting HTML strings, files, and even authenticated web pages into PDFs.

What are the key features of IronPDF for HTML to PDF conversion?

IronPDF offers key features such as support for HTML5, CSS, JavaScript, and complex page layouts. It also allows developers to convert HTML strings, URLs, and local HTML files into PDF documents with ease.

Can IronPDF handle authenticated web pages during conversion?

Yes, IronPDF can handle authenticated web pages. It supports converting pages that require authentication, ensuring secure and accurate PDF generation from protected web content.

How does IronPDF ensure the quality of converted PDFs?

IronPDF ensures high-quality PDF output by accurately rendering HTML content, including styles, fonts, and images, using advanced rendering engines. This ensures that the final PDF closely matches the original HTML layout.

Is it possible to convert HTML strings to PDF using IronPDF?

Yes, IronPDF can convert HTML strings directly into PDF documents. This feature is useful for dynamically generating PDFs from HTML content in web applications.

Does IronPDF support conversion of local HTML files to PDF?

IronPDF supports converting local HTML files to PDF by allowing developers to specify the file path. This feature makes it easy to generate PDFs from static HTML files stored on the server.

What programming languages does IronPDF support?

IronPDF is designed for use with C# and VB.NET, making it ideal for developers working within the .NET ecosystem to add PDF generation capabilities to their applications.

Can IronPDF handle complex HTML layouts and styles?

Yes, IronPDF is equipped to handle complex HTML layouts and styles, including CSS and JavaScript, ensuring that the resulting PDF maintains the design and functionality of the original web page.

What are some use cases for converting HTML to PDF in ASP.NET applications?

Some use cases include generating invoices, reports, and documentation from web pages, archiving web content, and creating downloadable PDF versions of web pages for offline use.

How does IronPDF compare to other HTML to PDF conversion tools?

IronPDF stands out with its ease of use, robust feature set, and excellent support for various HTML elements and authentication, providing a reliable solution for developers seeking high-quality PDF generation.

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