Skip to footer content
USING IRONPDF

How to Convert ASP HTML to PDF in .NET Core

Converting dynamic ASP.NET HTML to PDF documents is a fundamental requirement in modern ASP.NET applications. Whether you're generating invoices, creating reports, or producing downloadable PDF files, the ability to transform HTML content into professional PDF documents is essential for delivering polished user experiences.

IronPDF simplifies this ASP HTML to PDF conversion process by providing a robust, Chrome-based rendering engine that preserves your HTML formatting, CSS styling, and JavaScript functionality perfectly in the resulting PDF documents. This tutorial will walk you through effective methods for converting HTML to PDF in ASP.NET Core applications using the IronPDF library.

Why Do Developers Need HTML to PDF Conversion?

ASP.NET Core applications often generate dynamic HTML content that users need to download, share, or archive as PDF files. Converting HTML to PDF provides several key advantages over simply saving web pages or taking screenshots.

PDF documents maintain consistent formatting across all devices and platforms, ensuring your invoices look identical whether viewed on Windows, Mac, or mobile devices. They're also ideal for existing documents requiring digital signatures, security settings, or professional printing. Server-side PDF conversion eliminates the need for users to have specific software installed and provides better control over the final PDF file output.

Common use cases include generating financial reports from dashboard data, creating downloadable invoices from order information, producing tickets and passes with QR codes, and converting form submissions into permanent records. By handling the ASP HTML to PDF conversion on the server, you ensure consistent results regardless of the user's browser or device capabilities.

How Does IronPDF Installation Work?

Getting started with IronPDF in your ASP.NET Core project is straightforward. The library supports .NET Core 2.0 and above, along with .NET 5, 6, 7, and 8, making it compatible with all modern ASP.NET Core applications for HTML to PDF conversion tasks.

Installing via NuGet Package Manager

The quickest way to add IronPDF to your ASP.NET project for converting HTML to PDF is through the NuGet Package Manager in Visual Studio. Right-click on your project in Solution Explorer, select "Manage NuGet Packages," and search for IronPDF. Click Install on the latest version to add it to your project. For detailed installation instructions, see the IronPDF installation guide.

Install-Package IronPdf

Adding Required Namespaces

Once installed, add the IronPDF namespace to any C# file where you'll be working with PDF generation:

using IronPdf;
using IronPdf;
Imports IronPdf
$vbLabelText   $csharpLabel

This simple import statement gives you access to all of IronPDF's functionality, including the ChromePdfRenderer class for HTML conversion and various configuration options for customizing your PDF output.

Basic Configuration

For most ASP.NET Core applications, IronPDF works immediately after installation without additional configuration. However, you can set global options in your Program.cs or Startup.cs file:

// Optional: Configure IronPDF settings
Installation.TempFolderPath = @"C:\Temp\IronPdf\";
Installation.LinuxAndDockerDependenciesAutoConfig = true;
// Optional: Configure IronPDF settings
Installation.TempFolderPath = @"C:\Temp\IronPdf\";
Installation.LinuxAndDockerDependenciesAutoConfig = true;
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

These configuration options help optimize IronPDF for your specific hosting environment, whether you're running on Windows, Linux, or in Docker containers. Ensure both the script and application files don't reside in the same directory to prevent conflicts.

How to Convert HTML Strings to PDF?

The most fundamental operation in IronPDF is converting HTML strings directly to PDF documents. This approach is perfect when you're building HTML content dynamically in your ASP.NET application or working with HTML documents as templates.

// Create a PDF converter instance
var renderer = new ChromePdfRenderer();
// Convert HTML string to PDF document
var pdf = renderer.RenderHtmlAsPdf("<h1>Sales Report</h1><p>Generated on: " + DateTime.Now + "</p>");
// Save the resultant PDF document to a file
pdf.SaveAs("report.pdf");
// Create a PDF converter instance
var renderer = new ChromePdfRenderer();
// Convert HTML string to PDF document
var pdf = renderer.RenderHtmlAsPdf("<h1>Sales Report</h1><p>Generated on: " + DateTime.Now + "</p>");
// Save the resultant PDF document to a file
pdf.SaveAs("report.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This code snippet creates a new ChromePdfRenderer instance, which uses the Chromium engine to render your HTML content. The RenderHtmlAsPdf method accepts any valid HTML string and returns a PdfDocument object. You can then save this PDF file to disk or stream it directly to users as a byte array. Learn more about the ChromePdfRenderer class and its capabilities.

Working with CSS and Images

IronPDF fully supports CSS styling and can embed images from various sources when converting HTML to PDF. The PDF converter handles HTML elements with complete fidelity, including various HTML tags and image URLs:

var html = @"
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        h1 { color: #2c3e50; border-bottom: 2px solid #3498db; }
        .highlight { background-color: #f1c40f; padding: 5px; }
    </style>
    <h1>Monthly Report</h1>
    <p>This HTML document includes <span class='highlight'>highlighted text</span> and styling.</p>
    <img src='data:image/png;base64,iVBORw0KGgoAAAANS...' alt='Logo' />";
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(html);
var html = @"
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        h1 { color: #2c3e50; border-bottom: 2px solid #3498db; }
        .highlight { background-color: #f1c40f; padding: 5px; }
    </style>
    <h1>Monthly Report</h1>
    <p>This HTML document includes <span class='highlight'>highlighted text</span> and styling.</p>
    <img src='data:image/png;base64,iVBORw0KGgoAAAANS...' alt='Logo' />";
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(html);
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

The renderer processes inline styles, CSS files, and even base64-encoded images. This ensures your PDF pages maintain the exact appearance of your HTML content, including modern CSS3 features like flexbox and grid layouts. The HTML to PDF conversion preserves all HTML tags and their styling without generating blank pages.

How to Convert ASP.NET Core Views to PDF?

Converting entire ASP.NET Core web pages or views to PDF is a common requirement, especially for generating reports based on existing HTML documents. IronPDF provides several approaches for this ASP HTML to PDF conversion scenario, whether you're working with a single page or multiple pages.

Converting Controller Views

In your ASP.NET Core controller, you can render a view to HTML and then convert it to a PDF document using IronPDF's powerful PDF library rendering capabilities:

[HttpGet]
public async Task<IActionResult> DownloadPdf()
{
    var invoiceModel = new InvoiceModel
    {
        InvoiceNumber = 12345,
        Date = DateTime.Now,
        CustomerName = "Acme Corporation",
        Items = new List<InvoiceItem>
        {
            new InvoiceItem { Description = "Service", Quantity = 1, Price = 100.0 }
        },
        Total = 100.0
    };
    // Render the view to HTML string
    var htmlContent = await RenderViewToString("Invoice", invoiceModel);
    // Convert HTML to PDF
    var renderer = new ChromePdfRenderer();
    var pdf = renderer.RenderHtmlAsPdf(htmlContent);
    // Return PDF to browser
    var contentType = "application/pdf";
    var fileName = $"invoice_{DateTime.Now:yyyyMMdd}.pdf";
    return File(pdf.BinaryData, contentType, fileName);
}
private async Task<string> RenderViewToString(string viewName, object model)
{
    ViewData.Model = model;
    using (var writer = new StringWriter())
    {
        var viewResult = viewEngine.FindView(ControllerContext, viewName, false);
        var viewContext = new ViewContext(
            ControllerContext,
            viewResult.View,
            ViewData,
            TempData,
            writer,
            new HtmlHelperOptions()
        );
        await viewResult.View.RenderAsync(viewContext);
        return writer.GetStringBuilder().ToString();
    }
}
[HttpGet]
public async Task<IActionResult> DownloadPdf()
{
    var invoiceModel = new InvoiceModel
    {
        InvoiceNumber = 12345,
        Date = DateTime.Now,
        CustomerName = "Acme Corporation",
        Items = new List<InvoiceItem>
        {
            new InvoiceItem { Description = "Service", Quantity = 1, Price = 100.0 }
        },
        Total = 100.0
    };
    // Render the view to HTML string
    var htmlContent = await RenderViewToString("Invoice", invoiceModel);
    // Convert HTML to PDF
    var renderer = new ChromePdfRenderer();
    var pdf = renderer.RenderHtmlAsPdf(htmlContent);
    // Return PDF to browser
    var contentType = "application/pdf";
    var fileName = $"invoice_{DateTime.Now:yyyyMMdd}.pdf";
    return File(pdf.BinaryData, contentType, fileName);
}
private async Task<string> RenderViewToString(string viewName, object model)
{
    ViewData.Model = model;
    using (var writer = new StringWriter())
    {
        var viewResult = viewEngine.FindView(ControllerContext, viewName, false);
        var viewContext = new ViewContext(
            ControllerContext,
            viewResult.View,
            ViewData,
            TempData,
            writer,
            new HtmlHelperOptions()
        );
        await viewResult.View.RenderAsync(viewContext);
        return writer.GetStringBuilder().ToString();
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This approach renders your Razor view to an HTML string first and then converts it to PDF. The PDF is returned as a file download to the user's browser with an appropriate filename. This works seamlessly whether you're converting an ASPX file or modern Razor views.

Converting URLs to PDF

For existing web pages, you can use IronPDF as a powerful HTML to PDF converter to transform any specified URL directly into PDF files. Simply provide an HTTP or HTTPS address as the URL parameter:

[HttpGet]
public IActionResult GeneratePdfFromUrl()
{
    var renderer = new ChromePdfRenderer();
    // Convert a specified URL to PDF document
    var pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/");
    // Stream the PDF file to the browser
    return File(pdf.BinaryData, "application/pdf", "invoice.pdf");
}
[HttpGet]
public IActionResult GeneratePdfFromUrl()
{
    var renderer = new ChromePdfRenderer();
    // Convert a specified URL to PDF document
    var pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/");
    // Stream the PDF file to the browser
    return File(pdf.BinaryData, "application/pdf", "invoice.pdf");
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This method is particularly useful when you already have well-formatted web pages and want to offer them as a download PDF version. The .NET library handles all external resources, including stylesheets, scripts, and images, ensuring complete HTML rendering. The converter will return an appropriate HTTP status code if it encounters an invalid URL.

Handling Authentication

When converting authenticated pages with .NET forms authentication or other security mechanisms, you can pass cookies or headers to maintain the same user account session. This prevents redirection to a login screen during PDF conversion:

var renderer = new ChromePdfRenderer();
// Set cookies for authenticated requests with user database credentials
renderer.RenderingOptions.CustomCookies.Add("auth_token", Request.Cookies["auth_token"]);
// Convert protected web pages to PDF
var pdf = renderer.RenderUrlAsPdf("https://localhost:5001/secure/report");
var renderer = new ChromePdfRenderer();
// Set cookies for authenticated requests with user database credentials
renderer.RenderingOptions.CustomCookies.Add("auth_token", Request.Cookies["auth_token"]);
// Convert protected web pages to PDF
var pdf = renderer.RenderUrlAsPdf("https://localhost:5001/secure/report");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This ensures that protected HTML content can be converted to PDF files while maintaining security. The PDF conversion process respects your application's basic authentication and forms authentication, preventing unauthorized user account access to sensitive existing documents. You can also pass username and password arguments when needed for basic authentication scenarios.

How Can You Customize PDF Output?

IronPDF offers extensive customization options as a comprehensive PDF converter to control how your PDF documents are generated from HTML documents. These settings help you create professional PDF files that meet specific requirements for page layout and formatting.

Page Setup and Margins

var renderer = new ChromePdfRenderer();
// Set default page size for PDF pages
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Portrait;
// Control page width and margins for the resultant PDF document
renderer.RenderingOptions.MarginTop = 25;
renderer.RenderingOptions.MarginBottom = 25;
renderer.RenderingOptions.MarginLeft = 20;
renderer.RenderingOptions.MarginRight = 20;
var renderer = new ChromePdfRenderer();
// Set default page size for PDF pages
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Portrait;
// Control page width and margins for the resultant PDF document
renderer.RenderingOptions.MarginTop = 25;
renderer.RenderingOptions.MarginBottom = 25;
renderer.RenderingOptions.MarginLeft = 20;
renderer.RenderingOptions.MarginRight = 20;
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

These settings control the physical layout of your PDF pages, including both odd and even pages. You can choose from standard paper sizes or define custom dimensions, set portrait or landscape orientation, and adjust margins to match your design requirements for multiple pages. The graphics template system ensures consistent styling across subsequent odd pages and even pages.

Headers and Footers

Adding consistent headers and footers enhances the professional appearance of your PDF documents when converting HTML documents:

renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
{
    HtmlFragment = "<div style='text-align: center'>Company Report</div>",
    MaxHeight = 20
};
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter()
{
    HtmlFragment = "<div style='text-align: center'>Page {page} of {total-pages}</div>",
    MaxHeight = 20
};
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
{
    HtmlFragment = "<div style='text-align: center'>Company Report</div>",
    MaxHeight = 20
};
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter()
{
    HtmlFragment = "<div style='text-align: center'>Page {page} of {total-pages}</div>",
    MaxHeight = 20
};
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Headers and footers support HTML elements and formatting with special placeholders for page numbers, dates, and other dynamic content across all PDF pages. The following code demonstrates how to add professional headers to your dynamically generated document or existing PDF documents.

What Are the Best Practices?

To ensure optimal performance and quality when converting HTML to PDF, follow these proven practices for successful PDF conversion.

Always test your HTML rendering in a browser first to verify styling and layout before generating PDF files. Use absolute URLs for external resources when possible, as relative paths can cause issues during the HTML to PDF conversion process. For complex JavaScript-heavy web pages with multiple HTML elements, add render delays to ensure complete loading. Consider implementing caching for frequently generated PDF documents to reduce server load. For more ASP.NET Core best practices with this .NET library, refer to Microsoft's official documentation.

When deploying to production, configure appropriate temp folder paths and ensure your hosting environment has necessary dependencies installed for the PDF library, especially for Linux deployments. Avoid placing both the script and conversion logic in the same directory to prevent conflicts. Check our troubleshooting guide for common deployment scenarios with existing PDF documents. Always validate that input is not a URL when you intend to process direct HTML content to avoid unexpected behavior.

Conclusion

Converting ASP HTML to PDF in ASP.NET Core applications becomes straightforward with IronPDF. The library's Chrome-based rendering ensures accurate conversion while providing extensive customization options for professional document generation.

Whether working with HTML strings, a URL, or full web pages, IronPDF preserves exact formatting, CSS styling, and JavaScript behavior. This .NET-based web application tool handles the entire PDF conversion process efficiently.

Start your free 30-day trial or book a demo with our team.

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