Skip to footer content
USING IRONPDF

How to Create a PDF in ASP.NET C#

If you've ever struggled with the headache of 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 a constant, but the complexity of traditional PDF APIs often gets in the way.

Fortunately, IronPDF cuts through that complexity. This powerful .NET PDF library simplifies the entire process, giving you the complete code and tools to generate gorgeous, reliable PDF documents quickly.

What Makes PDF Generation Essential in ASP.NET Core?

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 convert HTML content directly to PDF format opens up powerful possibilities. You can leverage 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.

How Does IronPDF Simplify PDF Creation?

IronPDF stands out among other PDF generating 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 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. It is a powerful open-source library for many developers.

How to Get Started with IronPDF in ASP.NET Core?

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:

Install-Package IronPdf

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.

How to Create PDF Documents from Simple HTML String?

Let's start with a simple example that demonstrates how to create a PDF file from an HTML string. This example shows the fundamental approach to generating PDF documents:

using IronPdf;

public class PdfGenerator
{
    public void CreateSimplePdf()
    {
        // Create a new PDF document
        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;

public class PdfGenerator
{
    public void CreateSimplePdf()
    {
        // Create a new PDF document
        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");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Output PDF

How to Create a PDF in ASP.NET C#: Figure 1 - Simple HTML to PDF output

This code creates a new document with basic HTML content. 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. You can also find helpful PDF tutorials with complete code examples on our website.

How to Generate PDF Documents with Complex HTML?

IronPDF excels at rendering complex HTML content into PDF documents. Let's create a more sophisticated invoice document that demonstrates the library's capabilities with styled HTML content:

using IronPdf;
using System;

public class InvoiceGenerator
{
    public void CreateInvoiceDocument()
    {
        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.ToString("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>";
        // Generate PDF file
        var document = renderer.RenderHtmlAsPdf(htmlContent);
        document.SaveAs("invoice.pdf");
    }
}
using IronPdf;
using System;

public class InvoiceGenerator
{
    public void CreateInvoiceDocument()
    {
        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.ToString("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>";
        // Generate PDF file
        var document = renderer.RenderHtmlAsPdf(htmlContent);
        document.SaveAs("invoice.pdf");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Output PDF File

How to Create a PDF in ASP.NET C#: Figure 2 - Complex HTML to PDF output

The above 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.

How to Generate PDF Files in ASP.NET Core MVC Controllers?

In ASP.NET Core MVC applications, you'll typically generate PDF files within controller actions and return them to users for download. The following code snippet shows how to implement PDF generation in your controllers using the latest version:

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

public class DocumentController : Controller
{
    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>";
        // Create PDF document
        var pdfDocument = renderer.RenderHtmlAsPdf(htmlString);
        // Convert to byte array
        byte[] pdfBytes = pdfDocument.BinaryData;
        // Return file
        return File(pdfBytes, "application/pdf", "sales-report.pdf");
    }
}
using Microsoft.AspNetCore.Mvc;
using IronPdf;
using System.IO;

public class DocumentController : Controller
{
    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>";
        // Create PDF document
        var pdfDocument = renderer.RenderHtmlAsPdf(htmlString);
        // Convert to byte array
        byte[] pdfBytes = pdfDocument.BinaryData;
        // Return file
        return File(pdfBytes, "application/pdf", "sales-report.pdf");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

ASP.NET PDF Output

How to Create a PDF in ASP.NET C#: Figure 3 - ASP.NET HTML to PDF 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 format output. The file name for the download is "sales-report.pdf".

How to Easily Generate PDF Files from URLs and HTML Files?

IronPDF can also convert existing web pages and HTML files directly to PDF format. This is particularly useful when you need to generate PDFs from existing content:

using IronPdf;

public class WebPageConverter
{
    public void ConvertUrlToPdf()
    {
        var renderer = new ChromePdfRenderer();
        renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Screen;
        renderer.RenderingOptions.EnableJavaScript = true;
        renderer.RenderingOptions.WaitFor.RenderDelay(1000);
        // Convert URL to PDF
        var urlPdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page");
        urlPdf.SaveAs("webpage.pdf");
    }

    public void ConvertHtmlFileToPdf()
    {
        var renderer = new ChromePdfRenderer();
        // Convert HTML file to PDF
        var htmlFile = renderer.RenderHtmlFileAsPdf("template.html");
        htmlFile.SaveAs("from-file.pdf");
    }
}
using IronPdf;

public class WebPageConverter
{
    public void ConvertUrlToPdf()
    {
        var renderer = new ChromePdfRenderer();
        renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Screen;
        renderer.RenderingOptions.EnableJavaScript = true;
        renderer.RenderingOptions.WaitFor.RenderDelay(1000);
        // Convert URL to PDF
        var urlPdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page");
        urlPdf.SaveAs("webpage.pdf");
    }

    public void ConvertHtmlFileToPdf()
    {
        var renderer = new ChromePdfRenderer();
        // Convert HTML file to PDF
        var htmlFile = renderer.RenderHtmlFileAsPdf("template.html");
        htmlFile.SaveAs("from-file.pdf");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

URL to PDF Output

How to Create a PDF in ASP.NET C#: Figure 4 - URL to PDF output

Both methods preserve the complete code layout, images, and styling of the original content when creating PDF files. If an error occurred, be sure to check the file path.

How to Add Headers and Footers to PDF Documents?

Adding professional headers and footers to your PDF documents enhances their appearance and provides important context like page numbers and document titles. The following code example shows how we can do this:

using IronPdf;

public class HeaderFooterExample
{
    public void CreatePdfWithHeaderFooter()
    {
        var renderer = new ChromePdfRenderer();
        // Configure headers and footers
        renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
        {
            MaxHeight = 25,
            HtmlFragment = "<div style='text-align:center'>Company Report</div>",
            DrawDividerLine = true
        };
        renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter()
        {
            MaxHeight = 25,
            HtmlFragment = "<div style='text-align:center'>Page {page} of {total-pages}</div>",
            DrawDividerLine = true
        };
        // HTML content for the main document
        string content = "<h1>Annual Report</h1><p>This document contains important information.</p>";
        // Generate PDF with headers and footers
        var doc = renderer.RenderHtmlAsPdf(content);
        doc.SaveAs("report-with-headers.pdf");
    }
}
using IronPdf;

public class HeaderFooterExample
{
    public void CreatePdfWithHeaderFooter()
    {
        var renderer = new ChromePdfRenderer();
        // Configure headers and footers
        renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
        {
            MaxHeight = 25,
            HtmlFragment = "<div style='text-align:center'>Company Report</div>",
            DrawDividerLine = true
        };
        renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter()
        {
            MaxHeight = 25,
            HtmlFragment = "<div style='text-align:center'>Page {page} of {total-pages}</div>",
            DrawDividerLine = true
        };
        // HTML content for the main document
        string content = "<h1>Annual Report</h1><p>This document contains important information.</p>";
        // Generate PDF with headers and footers
        var doc = renderer.RenderHtmlAsPdf(content);
        doc.SaveAs("report-with-headers.pdf");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Output PDF with Headers

How to Create a PDF in ASP.NET C#: Figure 5 - Generated PDF with headers

The {page} and {total-pages} placeholders automatically populate with the correct page numbers, creating professional-looking PDF files. This allows you to add a new page to an existing document object.

Conclusion

The process behind creating PDF ASP.NET C# tasks with IronPDF transforms what could be a 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. You can also manage digital signatures easily. The use of a console application template or ASP.NET is flexible.

Whether you're generating PDFs for business reports, creating PDF documents from web pages, or converting HTML content to portable document format, IronPDF provides all the tools you need. Ready to start creating professional PDF files in your .NET applications?

Install IronPDF today and experience how easy PDF generation can be with the right .NET library. Check the good documentation for more details. IronPDF supports both .NET Framework and .NET Core.

For production deployments, explore the comprehensive licensing options that best suit your project needs. With IronPDF, you're just a few lines of code away from powerful PDF document generation in your ASP.NET Core applications.

Frequently Asked Questions

What is the best way to create PDFs in ASP.NET C#?

Using IronPDF allows developers to easily create PDFs in ASP.NET C# by converting HTML to PDF and generating professional documents with a simple API and Chrome rendering.

Can I convert HTML to PDF using IronPDF?

Yes, IronPDF provides a straightforward method to convert HTML to PDF, which is ideal for generating invoices, reports, and other professional documents.

What are the benefits of using IronPDF for generating PDFs?

IronPDF offers a simple API, Chrome rendering, and the ability to produce high-quality PDFs from HTML content, making it perfect for creating professional documents in ASP.NET C#.

Is it possible to generate invoices using IronPDF in ASP.NET C#?

Absolutely, IronPDF can generate professional invoices by converting HTML invoice templates into PDFs with ease.

How does IronPDF simplify the PDF creation process?

IronPDF simplifies the PDF creation process by providing a user-friendly API that converts HTML to PDF, eliminating the complexities of traditional PDF APIs.

What kind of documents can be generated with IronPDF?

With IronPDF, you can generate a wide range of documents such as professional invoices, detailed reports, and official documents by converting HTML to PDF.

Does IronPDF use Chrome for rendering PDFs?

Yes, IronPDF utilizes Chrome rendering to ensure high-quality PDF output from HTML content.

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