Skip to footer content
USING IRONPDF

How to Create a PDF in .NET with C#

In most modern .NET projects, you’ll eventually need to create and manipulate PDF documents. Whether that means building simple PDF documents, merging multiple PDFs into a single document, or ensuring your app can handle multilingual PDF documents across major operating systems. It doesn't matter if it's an invoice, a customer report, or a snapshot of web content, having a reliable way to build PDFs saves time and makes your app feel professional.

Developers often hit a few roadblocks here: keeping layouts consistent across different machines, dealing with images and tables, or making sure JavaScript-driven content shows up correctly in the final document. Picking the right .NET PDF library for C# PDF creation can help you avoid dealing with the pain of these issues.

In this article, we'll be covering how you can create PDF documents in .NET applications with IronPDF. First, we’ll start with basic HTML-to-PDF conversion, then move on to adding advanced features like headers, footers, and security. By the end of our time together today, you'll be a pro at PDF creation with IronPDF.

What Are the Main Approaches to Creating PDFs in .NET?

How to Create a PDF in .NET with C#: Figure 1 - PDF creation main approaches

When developing PDF generation capabilities in .NET applications, developers typically choose between three primary approaches. HTML to PDF conversion leverages existing web technologies, allowing you to design documents using familiar HTML and CSS before converting them to PDF format. Programmatic document building involves constructing PDFs element by element through code, offering precise control over every aspect of the document. Template-based generation combines predefined document templates with dynamic data, ideal for creating standardized documents like invoices or certificates.

The HTML to PDF approach has emerged as the preferred method for most modern applications. It eliminates the learning curve associated with PDF-specific APIs while enabling developers to leverage their existing web development skills. This method also ensures consistency between web views and generated PDFs, particularly important when creating customer-facing documents that need to match your application's design language.

IronPDF streamlines all three approaches through its comprehensive API, but truly excels at HTML to PDF conversion by using a Chrome-based rendering engine that produces pixel-perfect results. This means your PDFs will look exactly as they would when printed from Google Chrome, complete with proper CSS3 styling and JavaScript execution.

These methods give developers full support for popular document formats like XML Paper Specification, Microsoft Word, and Adobe Acrobat alternatives, ensuring compatibility with existing PDF documents and other file formats.

How Does IronPDF Make PDF Creation Simple and Powerful?

IronPDF revolutionizes PDF generation in .NET by combining enterprise-grade capabilities with an intuitive API that developers can master quickly. At its core, IronPDF uses the same Chromium engine that powers Google Chrome, ensuring that your HTML renders identically to how it appears in the world's most popular browser. This eliminates the common frustrations of CSS compatibility issues and JavaScript rendering problems that plague other PDF libraries.

The library's architecture prioritizes developer productivity without sacrificing functionality. Unlike libraries that require extensive PDF format knowledge or complex positioning calculations, IronPDF allows you to work with familiar web technologies. You write HTML and CSS as you normally would, and IronPDF handles the intricate details of PDF generation behind the scenes.

Setting up IronPDF in your .NET 9 project takes just minutes. Open your Package Manager Console and run:

Install-Package IronPdf

How to Create a PDF in .NET with C#: Figure 2 - IronPDF NuGet installation

Once installed, you're immediately ready to start generating PDFs. The library includes all necessary dependencies and requires no additional configuration for standard use cases. It supports .NET 9, .NET 8, .NET 7, .NET 6, .NET 5, .NET Core, .NET Standard, and .NET Framework 4.6.2+, ensuring compatibility with virtually any .NET project.

NuGet Install with NuGet

PM >  Install-Package IronPdf

Check out IronPDF on NuGet for quick installation. With over 10 million downloads, it’s transforming PDF development with C#. You can also download the DLL or Windows installer.

How to Convert HTML to PDF Files

Converting HTML content directly to PDF represents the most straightforward path to document generation in .NET. This approach shines when you need to create PDF documents dynamically based on user input, database content, or API responses. IronPDF's ChromePdfRenderer class makes this process remarkably simple while providing extensive customization options.

Here's how to generate a PDF from an HTML string containing a styled invoice:

using IronPdf;
using IronPdf.Rendering;
// Initialize the Chrome renderer
var renderer = new ChromePdfRenderer();
// Configure rendering options for professional output
renderer.RenderingOptions.MarginTop = 10;
renderer.RenderingOptions.MarginBottom = 10;
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;
// Create HTML content with embedded CSS
string htmlContent = @"
    <html>
    <head>
        <style>
            body { font-family: Arial, sans-serif; }
            .header { background-color: #2c3e50; color: white; padding: 20px; }
            .content { padding: 20px; }
            table { width: 100%; border-collapse: collapse; }
            th, td { padding: 10px; text-align: left; border-bottom: 1px solid #ddd; }
        </style>
    </head>
    <body>
        <div class='header'>
            <h1>Invoice #2024-001</h1>
        </div>
        <div class='content'>
            <table>
                <tr><th>Item</th><th>Quantity</th><th>Price</th></tr>
                <tr><td>Professional License</td><td>1</td><td>$749</td></tr>
            </table>
        </div>
    </body>
    </html>";
// Generate the PDF
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
// Save to file
pdf.SaveAs("invoice.pdf");
using IronPdf;
using IronPdf.Rendering;
// Initialize the Chrome renderer
var renderer = new ChromePdfRenderer();
// Configure rendering options for professional output
renderer.RenderingOptions.MarginTop = 10;
renderer.RenderingOptions.MarginBottom = 10;
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;
// Create HTML content with embedded CSS
string htmlContent = @"
    <html>
    <head>
        <style>
            body { font-family: Arial, sans-serif; }
            .header { background-color: #2c3e50; color: white; padding: 20px; }
            .content { padding: 20px; }
            table { width: 100%; border-collapse: collapse; }
            th, td { padding: 10px; text-align: left; border-bottom: 1px solid #ddd; }
        </style>
    </head>
    <body>
        <div class='header'>
            <h1>Invoice #2024-001</h1>
        </div>
        <div class='content'>
            <table>
                <tr><th>Item</th><th>Quantity</th><th>Price</th></tr>
                <tr><td>Professional License</td><td>1</td><td>$749</td></tr>
            </table>
        </div>
    </body>
    </html>";
// Generate the PDF
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
// Save to file
pdf.SaveAs("invoice.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This approach allows you to convert HTML to PDF files with just a few lines of C# code. IronPDF supports image formats such as PNG and JPEG, scalable vector graphics (SVG), and custom fonts, giving you precise control over document layout and file size.

The ChromePdfRenderer automatically processes your CSS, including modern CSS3 features like flexbox and grid layouts. It handles external stylesheets, embedded styles, and inline CSS with equal proficiency. The rendering engine executes JavaScript, allowing you to include dynamic content generation or client-side calculations in your HTML.

For more complex scenarios involving external assets, IronPDF provides the base URL parameter:

// Render HTML with external images and stylesheets
var pdf = renderer.RenderHtmlAsPdf(htmlContent, @"C:\Assets\");
// Render HTML with external images and stylesheets
var pdf = renderer.RenderHtmlAsPdf(htmlContent, @"C:\Assets\");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This tells IronPDF where to find referenced images, CSS files, and other resources, ensuring all elements render correctly in the final PDF. The library also supports embedding images as Base64 directly in your HTML for completely self-contained documents.

Output

How to Create a PDF in .NET with C#: Figure 3 - HTML to PDF output

How Do You Generate PDFs from URLs and Web Pages?

Converting live web pages to PDF opens powerful possibilities for documentation, archiving, and report generation. IronPDF excels at this task, handling everything from simple static pages to complex single-page applications with heavy JavaScript usage. The library waits for page resources to load and JavaScript to execute, ensuring you capture the fully rendered page.

Creating a PDF from a URL requires just a few lines of code:

using IronPdf;
var renderer = new ChromePdfRenderer();
// Configure for optimal web page capture
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
renderer.RenderingOptions.EnableJavaScript = true;
renderer.RenderingOptions.WaitFor.JavaScript(3000); // Wait for JavaScript
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;
// Convert URL to PDF
var pdf = renderer.RenderUrlAsPdf("https://apple.com");
pdf.SaveAs("website-capture.pdf");
using IronPdf;
var renderer = new ChromePdfRenderer();
// Configure for optimal web page capture
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
renderer.RenderingOptions.EnableJavaScript = true;
renderer.RenderingOptions.WaitFor.JavaScript(3000); // Wait for JavaScript
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;
// Convert URL to PDF
var pdf = renderer.RenderUrlAsPdf("https://apple.com");
pdf.SaveAs("website-capture.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

The RenderDelay option proves invaluable when dealing with pages that load content asynchronously. By specifying a delay in milliseconds, you ensure that AJAX calls complete and dynamic content renders before the PDF generation begins. This feature sets IronPDF apart from simpler converters that might capture incomplete pages.

Output

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

How Can You Build PDFs Programmatically from Scratch?

While HTML to PDF conversion handles most use cases elegantly, sometimes you need precise control over document construction. IronPDF provides comprehensive APIs for building PDFs element by element, perfect for scenarios requiring exact positioning or when working with non-HTML data sources.

Programmatically creating new PDF documents gives developers full control over PDF objects, PDF strings, and document structure. This level of PDF manipulation is ideal when working with raw text or integrating multiple data sources into complex documents.

Creating a new PDF document and adding content programmatically:

using IronPdf;
// Start with a blank document
PdfDocument pdf = new PdfDocument(270, 270);
// Apply text stamps with precise positioning
TextStamper textStamper = new TextStamper()
{
    Text = "Confidential Document",
    FontSize = 40,
    Color = IronSoftware.Drawing.Color.Black,
    IsBold = true,
    Opacity = 50,
    VerticalAlignment = VerticalAlignment.Middle,
    HorizontalAlignment = HorizontalAlignment.Center
};
// Add images
ImageStamper imageStamper = new ImageStamper(new Uri("https://ironpdf.com/img/svgs/iron-pdf-logo.svg"))
{
    HorizontalAlignment = HorizontalAlignment.Center,
        VerticalAlignment = VerticalAlignment.Bottom
    };
// Apply the stamps
Stamper[] stamps = {textStamper, imageStamper };
pdf.ApplyMultipleStamps(stamps);
// Save the PDF
pdf.SaveAs("programmatic-document.pdf");
using IronPdf;
// Start with a blank document
PdfDocument pdf = new PdfDocument(270, 270);
// Apply text stamps with precise positioning
TextStamper textStamper = new TextStamper()
{
    Text = "Confidential Document",
    FontSize = 40,
    Color = IronSoftware.Drawing.Color.Black,
    IsBold = true,
    Opacity = 50,
    VerticalAlignment = VerticalAlignment.Middle,
    HorizontalAlignment = HorizontalAlignment.Center
};
// Add images
ImageStamper imageStamper = new ImageStamper(new Uri("https://ironpdf.com/img/svgs/iron-pdf-logo.svg"))
{
    HorizontalAlignment = HorizontalAlignment.Center,
        VerticalAlignment = VerticalAlignment.Bottom
    };
// Apply the stamps
Stamper[] stamps = {textStamper, imageStamper };
pdf.ApplyMultipleStamps(stamps);
// Save the PDF
pdf.SaveAs("programmatic-document.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This approach gives you complete control over element placement, layering, and formatting. You can build complex documents by combining multiple stamps, adjusting opacity for watermarks, and precisely controlling the position of each element on the page.

How to Create a PDF in .NET with C#: Figure 5 - Programmatically created PDF document

What Advanced Features Enhance Your PDF Documents?

Professional PDF documents often require sophisticated features beyond basic content rendering. IronPDF delivers enterprise-grade capabilities through simple, intuitive APIs that don't need deep PDF format knowledge. Let's explore the killer features that transform ordinary PDFs into professional documents.

Headers and Footers

Adding consistent headers and footers across all pages enhances document professionalism and navigation. IronPDF supports both text-based and HTML-based headers and footers:

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

The {page} and {total-pages} placeholders automatically populate with the correct values, eliminating manual page counting.

Output

How to Create a PDF in .NET with C#: Figure 6 - Headers and Footers output

Security and Encryption

Protecting sensitive documents requires robust security features. IronPDF implements industry-standard encryption and permission controls:

// Set document passwords and permissions
pdf.SecuritySettings.UserPassword = "user123";
pdf.SecuritySettings.OwnerPassword = "owner456";
// Configure detailed permissions
pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.NoPrint;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserFormData = false;
pdf.SecuritySettings.AllowUserAnnotations = false;
// Set document passwords and permissions
pdf.SecuritySettings.UserPassword = "user123";
pdf.SecuritySettings.OwnerPassword = "owner456";
// Configure detailed permissions
pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.NoPrint;
pdf.SecuritySettings.AllowUserCopyPasteContent = false;
pdf.SecuritySettings.AllowUserFormData = false;
pdf.SecuritySettings.AllowUserAnnotations = false;
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

These security settings ensure your documents remain confidential and tamper-resistant, meeting compliance requirements for sensitive business documents. According to Microsoft's security documentation, proper encryption is essential for protecting sensitive data in enterprise applications.

Secured Document Properties

How to Create a PDF in .NET with C#: Figure 7 - PDF security properties

Forms and Interactivity

Interactive forms let users fill out PDF form fields, submit form data, and even embed digital signatures for compliance. IronPDF simplifies form filling and ensures consistent document properties across net applications built on .NET Core, .NET Framework, or any other .NET component

Transform static documents into interactive PDF forms that users can complete digitally:

// HTML forms automatically convert to PDF forms
string formHtml = @"
    <form>
        <label>Name:</label>
        <label>Email:</label>
        <label>Subscribe:</label>
        <button type='submit'>Submit</button>
    </form>";
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
var interactivePdf = renderer.RenderHtmlAsPdf(formHtml);
// HTML forms automatically convert to PDF forms
string formHtml = @"
    <form>
        <label>Name:</label>
        <label>Email:</label>
        <label>Subscribe:</label>
        <button type='submit'>Submit</button>
    </form>";
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
var interactivePdf = renderer.RenderHtmlAsPdf(formHtml);
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Output

How to Create a PDF in .NET with C#: Figure 8 - Interactive PDF output

Which PDF Creation Method Should You Choose for Your Project?

Selecting the optimal PDF generation approach depends on your specific requirements and existing architecture. Each method offers distinct advantages that align with different project needs.

Choose HTML to PDF conversion when you have existing web content, need to maintain consistency with your web application's design, or want to leverage CSS for styling. This approach works exceptionally well for reports, invoices, and any document that benefits from responsive design principles. The ability to use familiar web technologies significantly reduces development time and maintenance overhead. Check out our HTML to PDF examples to see this in action.

Opt for programmatic generation when you need pixel-perfect control over element placement, are working with non-HTML data sources, or require complex layering and positioning. This method suits technical drawings, certificates with precise layouts, and documents requiring exact specifications. Our API reference provides comprehensive documentation for all programmatic features.

Consider URL to PDF conversion for capturing live data, creating website archives, or generating reports from existing web applications. This approach eliminates the need to recreate existing web functionality and ensures your PDFs always reflect the most current information.

For maximum flexibility, combine approaches within a single document. Begin by converting HTML to PDF for the main content, and then incorporate programmatic elements such as watermarks or stamps. This hybrid approach leverages the strengths of each method while maintaining code simplicity.

How to Create a PDF in .NET with C#: Figure 9 - PDF Creation approach

Get stated with IronPDF now.
green arrow pointer

Getting Started with IronPDF Today

Starting your PDF generation journey with IronPDF requires minimal setup, yet it delivers immediate results. IronPDF transforms PDF generation from a complex challenge into a straightforward task. Its Chrome-based rendering ensures perfect fidelity, while the intuitive API keeps your code clean and maintainable. Whether you're building a new application or enhancing an existing one, IronPDF provides the tools you need to deliver professional PDF functionality.

The library's extensive feature set goes beyond covering your basic .NET PDF creation needs. Explore our tutorials for in-depth guides on specific scenarios, browse code examples for ready-to-use solutions, or dive into the comprehensive documentation to master every aspect of PDF generation in .NET.

Ready to revolutionize your PDF generation workflow? Start your free trial today and experience the difference that pixel-perfect rendering and developer-friendly APIs make. With dedicated support and regular updates, you'll be generating professional PDFs in minutes, not hours.

For production deployments, explore our flexible licensing options also offers comprehensive document processing capabilities beyond PDFs, providing a complete solution for all your document manipulation requirements.

Chipego
Software Engineer
Chipego has a natural skill for listening that helps him to comprehend customer issues, and offer intelligent solutions. He joined the Iron Software team in 2023, after studying a Bachelor of Science in Information Technology. IronPDF and IronOCR are the two products Chipego has been focusing on, but his knowledge of ...Read More