Skip to footer content
USING IRONPDF

How to Convert HTML to PDF in ASP.NET using C# with IronPDF

In today's fast-paced ASP.NET environment, your applications can't afford to slow down when generating crucial documents like invoices or reports. You need a way to easily convert HTML to PDF that guarantees perfect formatting every single time, across all devices.

IronPDF is the C# PDF library built for this challenge. By utilizing a robust Chrome-based rendering engine, it transforms your dynamic HTML code into pixel-perfect PDF documents. We'll walk you through the simple steps to integrate IronPDF into your .NET project and start saving professional-grade PDFs directly today.

How Do I 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 the IronPDF NuGet Package Manager Console package:

Install-Package IronPdf

So, want to learn how to convert HTML to PDF in ASP.NET using C#? Here's a complete code snippet that demonstrates converting an HTML string to a PDF file in an ASP.NET Core MVC controller to get you started:

using IronPdf;
using Microsoft.AspNetCore.Mvc;
// your program.cs file
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
var app = builder.Build();
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
// in your controller file
public class PdfController : Controller
{
    public IActionResult GeneratePdf()
    {
        var renderer = new ChromePdfRenderer();
        // Convert HTML string to PDF
        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 PDF as file download
        return File(pdf.BinaryData, "application/pdf", "invoice.pdf");
    }
}
using IronPdf;
using Microsoft.AspNetCore.Mvc;
// your program.cs file
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
var app = builder.Build();
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
// in your controller file
public class PdfController : Controller
{
    public IActionResult GeneratePdf()
    {
        var renderer = new ChromePdfRenderer();
        // Convert HTML string to PDF
        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 PDF as file download
        return File(pdf.BinaryData, "application/pdf", "invoice.pdf");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Output PDF File

How to Convert HTML to PDF in ASP.NET using C# with IronPDF: Image 1 - Image 1 of 7 related to How to Convert HTML to PDF in ASP.NET using C# with IronPDF

Add image alt text

This code creates a simple controller that generates PDF documents directly from HTML strings. The ChromePdfRenderer class handles all the complex rendering, ensuring your HTML structure, CSS styles, and even JavaScript render correctly in the final PDF output.

What Are the Essential Methods for Different HTML Sources?

IronPDF provides three primary methods to convert HTML content into PDF format, each designed for specific scenarios you'll encounter in ASP.NET development.

Converting HTML Strings Dynamically

When working with dynamic content like database-driven reports, use RenderHtmlAsPdf to easily convert HTML strings directly:

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");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

PDF Output

How to Convert HTML to PDF in ASP.NET using C# with IronPDF: Image 2 - HTML string to PDF output

This approach is perfect for generating PDF documents from HTML pages templates populated with real-time data, form submissions, or any dynamically generated HTML content.

Converting HTML Files from Disk

For static HTML templates stored as files, use RenderHtmlFileAsPdf to convert HTML files directly:

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");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This method efficiently handles existing HTML files, automatically resolving relative URLs for CSS styles, images, and external resources.

Converting URLs to PDF

To capture entire web pages or render existing URLs as PDFs, use the URL conversion method:

var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.EnableJavaScript = true;
renderer.RenderingOptions.WaitFor.RenderDelay(1000); // Wait an extra second for JavaScript to load
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Screen;
var PDF = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page");
pdf.SaveAs("webpage.pdf");
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.EnableJavaScript = true;
renderer.RenderingOptions.WaitFor.RenderDelay(1000); // Wait an extra second for JavaScript to load
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Screen;
var PDF = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page");
pdf.SaveAs("webpage.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Output

How to Convert HTML to PDF in ASP.NET using C# with IronPDF: Image 3 - URL to PDF output

This powerful feature supports complex JavaScript rendering, making it ideal for converting single-page applications or dynamically loaded web content from a specified URL.

How Can I Handle Form Data and POST Requests?

Processing form data before PDF generation is common in ASP.NET applications. Here's how to handle POST method submissions and generate PDFs from the submitted data:

[HttpPost]
public IActionResult ProcessFormToPdf(OrderModel model)
{
    var renderer = new ChromePdfRenderer();
    // Build HTML from form data
    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);
    // Save to server and return download
    var fileName = $"order-{model.OrderId}.pdf";
    return File(pdf.BinaryData, "application/pdf", fileName);
}
[HttpPost]
public IActionResult ProcessFormToPdf(OrderModel model)
{
    var renderer = new ChromePdfRenderer();
    // Build HTML from form data
    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);
    // Save to server and return download
    var fileName = $"order-{model.OrderId}.pdf";
    return File(pdf.BinaryData, "application/pdf", fileName);
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Example View

How to Convert HTML to PDF in ASP.NET using C# with IronPDF: Image 4 - Example form UI

Example Output

How to Convert HTML to PDF in ASP.NET using C# with IronPDF: Image 5 - Example PDF output rendered from the form

What Advanced Features Enhance PDF Generation?

Adding Headers, Footers, and Watermarks

Professional PDF documents often require headers, footers, and watermarks. IronPDF makes these additions straightforward thanks to it's powerful editing features that makes manipulating PDF documents a breeze.

var renderer = new ChromePdfRenderer();
// Configure headers and footers
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>"
};
// Generate PDF
var PDF = renderer.RenderHtmlAsPdf(htmlContent);
// Add watermark
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();
// Configure headers and footers
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>"
};
// Generate PDF
var PDF = renderer.RenderHtmlAsPdf(htmlContent);
// Add watermark
pdf.ApplyWatermark("<h2 style='color:red;opacity:0.3'>CONFIDENTIAL</h2>",
    30, VerticalAlignment.Middle, HorizontalAlignment.Center);
pdf.SaveAs("report-with-watermark.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Watermarked Output

How to Convert HTML to PDF in ASP.NET using C# with IronPDF: Image 6 - Generated PDF with added Watermark and header/footers

These features transform basic HTML to PDF conversion into professional document generation, perfect for contracts, reports, and official documents.

Optimizing CSS and Print Media

To ensure your PDF output matches expectations, leverage CSS print media queries and responsive design principles:

var renderer = new ChromePdfRenderer();
// Configure CSS media type
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;
// Set viewport for responsive designs
renderer.RenderingOptions.ViewPortWidth = 1024;
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();
// Configure CSS media type
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;
// Set viewport for responsive designs
renderer.RenderingOptions.ViewPortWidth = 1024;
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);
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

PDF Output

How to Convert HTML to PDF in ASP.NET using C# with IronPDF: Image 7 - PDF with custom CSS formatting

Using print CSS ensures your PDF documents maintain professional formatting while hiding unnecessary web elements like navigation menus or interactive buttons. Features like page break inside can be controlled with CSS to ensure optimal rendering on the current page.

Why Choose IronPDF for ASP.NET PDF Generation?

IronPDF's Chrome-based rendering engine ensures accurate HTML to PDF conversion with full support for modern web standards. The library handles complex JavaScript, CSS3 animations, and responsive layouts that other PDF converters struggle with. Integration requires just a few lines of code, making it ideal for rapid development in your .NET project or .NET application.

The ChromePdfRenderer class provides extensive customization through its RenderingOptions property, allowing you to control paper size, margins, JavaScript execution, and rendering delays. This flexibility ensures your PDF output meets exact specifications whether generating simple invoices or complex multi-page reports.

The library even handles rendering entire web pages or smaller HTML snippets with equal fidelity, without leaving behind any temp files. This all makes it a powerful option for your HTML to PDF converter.

Conclusion

Converting HTML to PDF in ASP.NET C# with IronPDF streamlines document generation workflows while maintaining perfect visual fidelity. The library's simple API, combined with powerful rendering capabilities, makes it the ideal solution for any ASP.NET Core application requiring PDF generation. It's the perfect .NET wrapper for this task, whether you're developing for .NET Core, the .NET Framework, or building mobile apps.

You can also use it with the command line or directly within Visual Studio using Solution Explorer. You'll often use a pattern like var client (or var renderer) and a string url (or file name) in a method like static async Task Main to programmatically save PDF from your input HTML or url directly.

Start your free trial today and transform your HTML code into professional PDF documents. For production deployments, explore our licensing options to find the perfect fit for your project needs.

Frequently Asked Questions

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

You can use IronPDF to convert HTML to PDF in ASP.NET Core. It provides a simple API that ensures perfect formatting and professional results.

What makes IronPDF suitable for HTML to PDF conversion?

IronPDF is suitable for HTML to PDF conversion because it utilizes a powerful Chrome rendering engine, ensuring pixel-perfect PDFs that maintain the original layout and style.

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

Yes, IronPDF can generate invoices and reports by converting HTML content into accurately formatted PDFs, making it ideal for business applications.

Does IronPDF support responsive design for PDF generation?

IronPDF supports responsive design by accurately rendering HTML content into PDFs that adapt to various devices and screen sizes.

Can IronPDF handle complex HTML content?

IronPDF is capable of processing complex HTML content, including CSS and JavaScript, ensuring that the resulting PDFs match the original web page design.

How does IronPDF ensure fast PDF generation?

IronPDF ensures fast PDF generation by leveraging its efficient Chrome rendering engine, which processes HTML quickly and accurately without slowing down your ASP.NET applications.

What are the benefits of using IronPDF in a fast-paced ASP.NET environment?

In a fast-paced ASP.NET environment, IronPDF offers quick, reliable HTML to PDF conversion, ensuring that your applications maintain high performance and deliver professional-quality documents.

Does IronPDF provide support for different file formats?

IronPDF primarily focuses on converting HTML to PDF but also supports merging, splitting, and editing PDFs, providing a versatile solution for document management.

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