Skip to footer content
USING IRONPDF

How to Create a PDF in ASP.NET C# with IronPDF

IronPDF simplifies PDF generation in ASP.NET C# by providing a Chrome-based rendering engine that converts HTML, CSS, and JavaScript directly to PDF documents with just a few lines of code, eliminating the complexity of traditional PDF APIs.

If you've ever struggled with generating formatted PDF files in ASP.NET C#, you know how frustrating it can be. The need for professional invoices, detailed reports, and official documents is constant, but traditional PDF APIs often get in the way with their complexity.

Fortunately, IronPDF cuts through that complexity. This reliable .NET PDF library simplifies the entire process, giving you the complete code and tools to generate PDF documents quickly. Whether you're deploying to Azure or AWS, IronPDF provides solid integration across cloud platforms. The library also supports Docker deployments and can run as a remote container service for flexible architectures.

What Makes PDF Generation Essential in ASP.NET Core?

Why Do Businesses Need Server-Side PDF Generation?

PDF documents serve as the universal standard for sharing formatted content across different platforms and devices. In ASP.NET Core applications, generating PDF files enables businesses to create professional invoices, detailed reports, and official documents that maintain their formatting regardless of the viewing environment.

Server-side PDF generation provides consistent output, better security control, and eliminates dependency on client-side resources. The ability to add digital signatures and set PDF passwords ensures document integrity and confidentiality. PDF remains the most widely supported document format for business communication -- according to Adobe's documentation, the specification is an open ISO standard (ISO 32000), making it a reliable long-term choice for document exchange.

What Advantages Does HTML to PDF Conversion Offer?

The ability to convert HTML content to PDF directly opens up practical possibilities. You can use your existing HTML and CSS knowledge to create beautifully formatted PDF documents without learning complex PDF-specific APIs. This approach allows you to generate PDF files from your existing web pages, Razor views, or custom HTML strings with minimal effort.

IronPDF supports responsive CSS and handles JavaScript execution during conversion. The library enables conversion from CSHTML files in MVC Core and can process CSHTML headlessly for background operations. This makes it especially useful when your existing front-end templates already define the visual layout you want in the final PDF.

How Does a Chrome-Based Rendering Engine Simplify PDF Creation?

What Makes IronPDF's Rendering Engine Reliable?

IronPDF stands out among PDF libraries through its Chrome-based rendering engine that ensures accurate HTML to PDF conversion. This engine supports modern web standards including CSS3, JavaScript, and responsive layouts, making it possible to create PDF documents that look exactly like their HTML counterparts.

The rendering engine handles custom fonts, web fonts, and even complex WebGL content, ensuring pixel-perfect results. It's built on the same technology that powers Google Chrome, providing reliable pixel-perfect conversion. The engine also supports SVG graphics and Base64 encoded images for self-contained documents.

Why Is IronPDF Practical for .NET Developers?

The library's straightforward API design means you can start generating PDFs immediately without extensive configuration. IronPDF handles the complexities of PDF file creation behind the scenes, from managing fonts and images to properly rendering complex layouts. Whether you need to generate a PDF from a simple HTML string or convert entire web pages, the process remains consistently simple.

The complete documentation and tutorials make it straightforward to get started, while the API reference provides detailed information for advanced scenarios. A Quickstart guide offers a rapid introduction, and the library includes extensive code examples for common use cases.

How Do You Install a .NET PDF Library in ASP.NET Core?

What Are the Installation Options?

Setting up IronPDF in your ASP.NET Core project is straightforward using the NuGet Package Manager. Open your Package Manager Console in Visual Studio and run the following command, or use the .NET CLI:

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

For Windows, Linux, or macOS deployments, IronPDF provides platform-specific optimizations. You can also run IronPDF in Docker containers or as a remote service for flexible architectures. The library supports .NET 10 and runs on all major platforms supported by the .NET runtime.

Do You Need a License to Start Development?

Once installed, you'll have access to the complete IronPDF library and can immediately begin creating PDF files. For production use, you'll need to apply a license key, but the free version allows full development and testing. The licensing options include various tiers to suit different project needs, from individual developers to enterprise deployments.

Get stated with IronPDF now.
green arrow pointer

How Do You Create PDF Documents from HTML Strings?

What Is the Basic Code Pattern for PDF Generation?

The simplest way to get started is generating a PDF from an HTML string. This demonstrates the fundamental approach -- just a few lines of code produce a complete PDF document:

using IronPdf;

// Create a renderer
var renderer = new ChromePdfRenderer();

// Generate PDF from HTML string
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1><p>This is my first PDF file in C#!</p>");

// Save the PDF file
pdf.SaveAs("simple-document.pdf");
using IronPdf;

// Create a renderer
var renderer = new ChromePdfRenderer();

// Generate PDF from HTML string
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1><p>This is my first PDF file in C#!</p>");

// Save the PDF file
pdf.SaveAs("simple-document.pdf");
$vbLabelText   $csharpLabel

Simple HTML string converted to PDF document showing basic heading and paragraph text with default formatting in IronPDF

How Does the Rendering Process Work?

The ChromePdfRenderer class handles all the conversion details, transforming your HTML into a properly formatted PDF file. The resulting document maintains the HTML structure while converting it to the portable document format. For more advanced scenarios, you can set custom margins, configure paper sizes, or control page orientation using the renderer's RenderingOptions property. You can also save PDFs to memory streams for cloud storage scenarios or return them directly from a web endpoint.

How Do You Generate PDF Documents with Complex HTML?

How Do You Create a Professional Invoice PDF?

IronPDF excels at rendering complex HTML content into PDF documents. The following example creates a professional invoice document using top-level statements and C# raw string literals:

using IronPdf;

var renderer = new ChromePdfRenderer();

// HTML content with styling
string htmlContent = $"""
    <!DOCTYPE html>
    <html>
    <head>
        <style>
            body {{ font-family: Arial, sans-serif; margin: 40px; }}
            .header {{ background-color: #003366; color: white; padding: 20px; text-align: center; }}
            .invoice-details {{ margin: 20px 0; }}
            table {{ width: 100%; border-collapse: collapse; margin-top: 20px; }}
            th {{ background-color: #f0f0f0; padding: 10px; text-align: left; }}
            td {{ padding: 10px; border-bottom: 1px solid #ddd; }}
            .total {{ font-size: 18px; font-weight: bold; text-align: right; margin-top: 20px; }}
        </style>
    </head>
    <body>
        <div class='header'><h1>INVOICE</h1></div>
        <div class='invoice-details'>
            <p><strong>Invoice Number:</strong> INV-2024-001</p>
            <p><strong>Date:</strong> {DateTime.Now:yyyy-MM-dd}</p>
            <p><strong>Customer:</strong> ABC Corporation</p>
        </div>
        <table>
            <thead>
                <tr><th>Item</th><th>Quantity</th><th>Price</th><th>Total</th></tr>
            </thead>
            <tbody>
                <tr><td>Professional Services</td><td>10</td><td>$150.00</td><td>$1,500.00</td></tr>
                <tr><td>Software License</td><td>1</td><td>$499.00</td><td>$499.00</td></tr>
            </tbody>
        </table>
        <div class='total'>Total Amount: $1,999.00</div>
    </body>
    </html>
    """;

var document = renderer.RenderHtmlAsPdf(htmlContent);
document.SaveAs("invoice.pdf");
using IronPdf;

var renderer = new ChromePdfRenderer();

// HTML content with styling
string htmlContent = $"""
    <!DOCTYPE html>
    <html>
    <head>
        <style>
            body {{ font-family: Arial, sans-serif; margin: 40px; }}
            .header {{ background-color: #003366; color: white; padding: 20px; text-align: center; }}
            .invoice-details {{ margin: 20px 0; }}
            table {{ width: 100%; border-collapse: collapse; margin-top: 20px; }}
            th {{ background-color: #f0f0f0; padding: 10px; text-align: left; }}
            td {{ padding: 10px; border-bottom: 1px solid #ddd; }}
            .total {{ font-size: 18px; font-weight: bold; text-align: right; margin-top: 20px; }}
        </style>
    </head>
    <body>
        <div class='header'><h1>INVOICE</h1></div>
        <div class='invoice-details'>
            <p><strong>Invoice Number:</strong> INV-2024-001</p>
            <p><strong>Date:</strong> {DateTime.Now:yyyy-MM-dd}</p>
            <p><strong>Customer:</strong> ABC Corporation</p>
        </div>
        <table>
            <thead>
                <tr><th>Item</th><th>Quantity</th><th>Price</th><th>Total</th></tr>
            </thead>
            <tbody>
                <tr><td>Professional Services</td><td>10</td><td>$150.00</td><td>$1,500.00</td></tr>
                <tr><td>Software License</td><td>1</td><td>$499.00</td><td>$499.00</td></tr>
            </tbody>
        </table>
        <div class='total'>Total Amount: $1,999.00</div>
    </body>
    </html>
    """;

var document = renderer.RenderHtmlAsPdf(htmlContent);
document.SaveAs("invoice.pdf");
$vbLabelText   $csharpLabel

Professional business invoice PDF generated from complex HTML showing styled header, formatted table with itemized billing details, and calculated totals

Why Does CSS Styling Work So Well in PDF Output?

This code demonstrates how IronPDF handles complex HTML structures, CSS styling, and dynamic content to create professional PDF documents. The resulting PDF file maintains all formatting, making it perfect for business document generation. You can further improve documents by adding watermarks, applying stamps, or embedding images. IronPDF also supports UTF-8 and international languages, ensuring global compatibility.

For advanced layouts, you can use CSS print media to improve the PDF output, add barcodes, or create interactive forms. The library handles HTML ZIP archives and supports custom HTTP headers for authenticated content, making it flexible enough for production workflows.

How Do You Return PDFs from ASP.NET Core MVC Controllers?

What Is the Best Way to Stream a PDF to the Browser?

In ASP.NET Core MVC applications, you'll typically generate PDF files within controller actions and return them to users for download. The following example applies custom margins and CSS media settings, written using top-level statements:

using Microsoft.AspNetCore.Mvc;
using IronPdf;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
var app = builder.Build();
app.MapControllers();
app.Run();

[Route("documents")]
public class DocumentController : Controller
{
    [HttpGet("report")]
    public IActionResult GenerateReport()
    {
        var renderer = new ChromePdfRenderer();

        // Configure rendering options
        renderer.RenderingOptions.MarginTop = 25;
        renderer.RenderingOptions.MarginBottom = 25;
        renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;

        string htmlString = """
            <html>
            <head>
                <style>
                    body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
                    h1 { color: #2c3e50; }
                    .report-content { line-height: 1.6; }
                </style>
            </head>
            <body>
                <h1>Monthly Sales Report</h1>
                <div class='report-content'>
                    <p>This report contains confidential sales data for the current month.</p>
                    <p>Total Revenue: $45,678</p>
                    <p>New Customers: 123</p>
                </div>
            </body>
            </html>
            """;

        var pdfDocument = renderer.RenderHtmlAsPdf(htmlString);
        byte[] pdfBytes = pdfDocument.BinaryData;
        return File(pdfBytes, "application/pdf", "sales-report.pdf");
    }
}
using Microsoft.AspNetCore.Mvc;
using IronPdf;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
var app = builder.Build();
app.MapControllers();
app.Run();

[Route("documents")]
public class DocumentController : Controller
{
    [HttpGet("report")]
    public IActionResult GenerateReport()
    {
        var renderer = new ChromePdfRenderer();

        // Configure rendering options
        renderer.RenderingOptions.MarginTop = 25;
        renderer.RenderingOptions.MarginBottom = 25;
        renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;

        string htmlString = """
            <html>
            <head>
                <style>
                    body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
                    h1 { color: #2c3e50; }
                    .report-content { line-height: 1.6; }
                </style>
            </head>
            <body>
                <h1>Monthly Sales Report</h1>
                <div class='report-content'>
                    <p>This report contains confidential sales data for the current month.</p>
                    <p>Total Revenue: $45,678</p>
                    <p>New Customers: 123</p>
                </div>
            </body>
            </html>
            """;

        var pdfDocument = renderer.RenderHtmlAsPdf(htmlString);
        byte[] pdfBytes = pdfDocument.BinaryData;
        return File(pdfBytes, "application/pdf", "sales-report.pdf");
    }
}
$vbLabelText   $csharpLabel

ASP.NET MVC controller-generated PDF sales report with custom margins and print-improve CSS styling for professional business document output

How Do Rendering Options Affect the Output?

This controller action generates a PDF document and returns it as a downloadable file. The rendering options allow you to customize margins and specify the CSS media type for optimal PDF output. The implementation returns the file as "sales-report.pdf" for download using ASP.NET's File() method.

For more complex scenarios, you can export PDFs to memory for further processing or implement async PDF generation for better performance. IronPDF also supports ASPX page conversion for legacy applications and works well with Blazor Server applications for more modern architectures.

How Do You Generate PDFs from URLs and HTML Files?

Can You Convert an Existing Web Page to PDF?

IronPDF can also convert existing web pages and HTML files directly to PDF format. This approach provides clear benefits when you need to generate PDFs from existing content without rebuilding HTML from scratch:

using IronPdf;

var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Screen;
renderer.RenderingOptions.EnableJavaScript = true;
renderer.RenderingOptions.WaitFor.RenderDelay(1000);

// Convert a URL to PDF
var urlPdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/PDF");
urlPdf.SaveAs("webpage.pdf");

// Convert an HTML file to PDF
var htmlFilePdf = renderer.RenderHtmlFileAsPdf("template.html");
htmlFilePdf.SaveAs("from-file.pdf");
using IronPdf;

var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Screen;
renderer.RenderingOptions.EnableJavaScript = true;
renderer.RenderingOptions.WaitFor.RenderDelay(1000);

// Convert a URL to PDF
var urlPdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/PDF");
urlPdf.SaveAs("webpage.pdf");

// Convert an HTML file to PDF
var htmlFilePdf = renderer.RenderHtmlFileAsPdf("template.html");
htmlFilePdf.SaveAs("from-file.pdf");
$vbLabelText   $csharpLabel

Wikipedia page converted to PDF preserving complete web layout including navigation, images, and interactive elements with accurate Chrome-based rendering

What Should You Know About JavaScript Rendering?

Both methods preserve the complete layout, images, and styling of the original content when creating PDF files. The WaitFor class provides advanced options for handling dynamic content, while custom render delays ensure JavaScript-heavy pages render completely before the PDF is captured.

You can handle TLS website logins and work with cookies for authenticated content. The renderer supports Angular.js and other JavaScript frameworks, and can execute custom JavaScript prior to conversion. According to MDN Web Docs, HTML is the foundation of the web, which is why HTML-to-PDF libraries that support full web standards are the most versatile approach for document generation.

How Do You Add Headers and Footers to PDF Documents?

Why Are Headers and Footers Important for Professional Documents?

Adding professional headers and footers to your PDF documents improves their appearance and provides important context like page numbers and document titles. You can configure both through the renderer's rendering options:

using IronPdf;

var renderer = new ChromePdfRenderer();

// Configure header
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
{
    MaxHeight = 25,
    HtmlFragment = "<div style='text-align:center'>Company Report</div>",
    DrawDividerLine = true
};

// Configure footer with page number placeholders
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter()
{
    MaxHeight = 25,
    HtmlFragment = "<div style='text-align:center'>Page {page} of {total-pages}</div>",
    DrawDividerLine = true
};

string content = "<h1>Annual Report</h1><p>This document contains important information.</p>";
var doc = renderer.RenderHtmlAsPdf(content);
doc.SaveAs("report-with-headers.pdf");
using IronPdf;

var renderer = new ChromePdfRenderer();

// Configure header
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
{
    MaxHeight = 25,
    HtmlFragment = "<div style='text-align:center'>Company Report</div>",
    DrawDividerLine = true
};

// Configure footer with page number placeholders
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter()
{
    MaxHeight = 25,
    HtmlFragment = "<div style='text-align:center'>Page {page} of {total-pages}</div>",
    DrawDividerLine = true
};

string content = "<h1>Annual Report</h1><p>This document contains important information.</p>";
var doc = renderer.RenderHtmlAsPdf(content);
doc.SaveAs("report-with-headers.pdf");
$vbLabelText   $csharpLabel

Professional PDF document displaying custom HTML headers and footers with automatic page numbering and divider lines for polished business reports

How Do Page Number Placeholders Work?

The {page} and {total-pages} placeholders automatically populate with the correct page numbers, creating professional-looking PDF files. The library manages the complexity for you, allowing you to add page numbers to any document without manual calculation.

Beyond basic headers, you can add custom watermarks, implement page breaks, or create a table of contents for longer documents. IronPDF also supports adding attachments and creating PDF forms for interactive documents. You can work with advanced HTML headers for complex layouts, add annotations, or manage metadata. The library allows you to extract form data, draw shapes, and add text to existing PDFs.

What Are the Key PDF Generation Features for ASP.NET?

Which PDF Generation Methods Should You Use?

The following table summarizes the main PDF generation methods and scenarios supported by IronPDF in ASP.NET applications:

IronPDF PDF Generation Methods for ASP.NET
Method Use Case Key Benefit
RenderHtmlAsPdf Generate from HTML string or template Full CSS and JavaScript support
RenderUrlAsPdf Convert existing web pages to PDF Preserves live page layout exactly
RenderHtmlFileAsPdf Convert local HTML files to PDF Works offline with local assets
Headers and Footers Add page numbers and titles Automatic placeholder substitution
MVC Controller return Stream PDF directly to browser No file system required

Creating PDFs in ASP.NET C# with IronPDF turns a potentially complex task into a straightforward process. From simple HTML strings to complex invoice documents, IronPDF's Chrome rendering engine ensures your PDF documents look exactly as intended. The library's intuitive API allows you to generate PDF files, modify PDF files, and handle existing PDF documents with minimal code.

IronPDF supports advanced features like PDF compression, linearization, and PDF/A compliance for archival purposes. The library offers complete document organization features, supports multiple image formats, and can extract text and images from existing PDFs. For specialized needs, you can work with grayscale conversion, DOCX to PDF conversion, or even Markdown to PDF transformation.

IronPDF supports both .NET Framework and .NET 10, making it a long-term choice for any ASP.NET project. The Microsoft .NET documentation highlights .NET 10 as a Long Term Support release, reinforcing that libraries built for it will remain relevant for years. You can also explore PDF to HTML conversion, rasterizing PDFs to images, and printing to physical printers.

How Do You Get Started with a Free Trial?

Ready to start creating professional PDF files in your .NET applications? You can download IronPDF for free and begin generating PDF documents today -- no payment required to evaluate the full feature set.

Explore the demos to see IronPDF in action, or dive into the code examples for practical implementations. Check out comparisons with other libraries to understand where IronPDF fits your requirements.

Install IronPDF from NuGet today and experience how approachable PDF generation can be with the right .NET library. For production deployments, review the complete licensing options that best suit your project needs. The library provides complete troubleshooting guides for common issues and engineering support for complex scenarios.

Frequently Asked Questions

What is IronPDF and how does it help in creating PDFs in ASP.NET C#?

IronPDF is a library that simplifies the process of creating and manipulating PDF files in ASP.NET C#. It allows for seamless conversion of HTML to PDF, enabling developers to generate professional documents, invoices, and reports with ease.

How can I convert HTML to PDF using IronPDF in ASP.NET C#?

To convert HTML to PDF using IronPDF in ASP.NET C#, you can utilize its simple API that leverages Chrome rendering. This ensures high-quality, accurate PDF outputs from HTML content.

What are the benefits of using IronPDF over traditional PDF APIs?

IronPDF offers a more straightforward and efficient approach to PDF generation compared to traditional APIs. It reduces complexity by providing a simple API interface and robust features like Chrome-based rendering, making it easier to produce professional-grade PDFs.

Can IronPDF handle the creation of professional invoices and reports?

Yes, IronPDF is specifically designed to handle the creation of professional invoices, detailed reports, and other official documents, making it a valuable tool for businesses that require well-formatted PDFs.

What rendering engine does IronPDF use for converting HTML to PDF?

IronPDF uses a Chrome rendering engine to convert HTML to PDF, ensuring that the resulting PDFs are accurate and maintain the styling of the original HTML content.

Is IronPDF suitable for generating complex PDF documents?

Absolutely, IronPDF is well-suited for generating complex PDF documents. Its powerful features allow developers to create intricate layouts and designs, maintaining the quality and professionalism of the document.

Why should developers choose IronPDF for PDF generation in ASP.NET C#?

Developers should choose IronPDF for its ease of use, reliability, and the ability to produce high-quality PDFs quickly. The library's simple API and robust feature set make it an ideal choice for ASP.NET C# projects.

How does IronPDF simplify the PDF creation process in ASP.NET C#?

IronPDF simplifies the PDF creation process by providing an intuitive API that reduces the complexity typically associated with traditional PDF libraries, allowing developers to focus on design and functionality instead of technical hurdles.

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