Skip to footer content
USING IRONPDF

C# PDFWriter Tutorial: Create PDF Documents in .NET

IronPDF simplifies the process of creating PDFs in C# by converting HTML to PDF, allowing developers to generate professional PDFs with minimal code, avoiding manual positioning or excessive boilerplate.

Creating PDF documents programmatically in C# used to be challenging. Most C# PDFWriter solutions involve complex APIs and extensive boilerplate code just to produce a simple PDF file. If you've tried older open-source libraries, you know how frustrating it can be with memory leaks and performance issues.

IronPDF changes all that. With just a few lines of code, you can create PDF documents, add new pages, paragraphs, images, headers, and page numbers, and save them without dealing with low-level details. The library supports async operations for better performance and multithreading for batch processing.

In this article, we'll show you how to use IronPDF's document object, ChromePdfRenderer, and PDF generation methods to make professional PDF documents in .NET Framework or .NET Core, directly from Visual Studio. By the end, you'll be ready to generate your own PDF files, whether it's a quick "Hello World" test or a full-fledged invoice with custom fonts and embedded images.

What is a PDFWriter in C#?

A PDFWriter is a document object that lets developers generate PDF documents, add paragraphs, images, headers, and manipulate pages programmatically. Traditional libraries often require manual positioning, complex calculations, and explicit resource management. They may also struggle with international languages and UTF-8 support.

IronPDF simplifies all of this. You can create PDF documents using HTML content and CSS with simple code from a familiar C# environment like your typical console application or working with standard classes like MemoryStream. The library handles font kerning and metadata management automatically.

Some libraries, like iTextSharp, have a class named PdfWriter, but in C# the term PDFWriter generally refers to any component or library that programmatically generates PDF documents. If you're comparing options, check out how IronPDF compares to iText, or see comparisons with Aspose, Syncfusion, and QuestPDF for a detailed feature analysis.

Moving from low-level manipulation to high-level generation boosts productivity. With a new PdfDocument instance in Visual Studio or your IDE, you can create PDFs with minimal code. The Chrome rendering engine ensures pixel-perfect output every time, supporting modern CSS media types and responsive layouts.

As shown below, traditional PDFWriter libraries like iTextSharp need lots of boilerplate, while IronPDF produces the same PDF document in just a few lines—faster, simpler, and less error-prone. The library also provides custom logging options and native exception handling for easier debugging.

How to Install IronPDF in Your C# Project?

Getting started with IronPDF takes less than a minute. The simplest installation method uses NuGet Package Manager:

Install-Package IronPdf

Alternatively, in Visual Studio:

  1. Right-click your project in Solution Explorer
  2. Select "Manage NuGet Packages"
  3. Search for "IronPDF"
  4. Click Install

For detailed platform-specific installations, check the IronPDF installation guide and advanced NuGet configuration. If you're deploying to Azure or Azure Functions, AWS or AWS Lambda, or need to run IronPDF in Docker, we have specific guides for each environment. For Linux deployments including Red Hat Enterprise Linux or macOS installations on Intel and Apple Silicon, additional dependencies may be required. You can also use the Windows Installer for manual setup.

How to Create Your First PDF with IronPDF?

Unlike traditional PDFWriter implementations, in IronPDF you don't need a separate PDFWriter class variable. The renderer and PdfDocument objects handle all writing tasks internally. Here's a complete working example:

using IronPdf;
// Instantiate the PDF renderer
var renderer = new ChromePdfRenderer();
// Create PDF from HTML string
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1><p>This is my first PDF!</p>");
// Save the PDF
pdf.SaveAs("output.pdf");
using IronPdf;
// Instantiate the PDF renderer
var renderer = new ChromePdfRenderer();
// Create PDF from HTML string
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1><p>This is my first PDF!</p>");
// Save the PDF
pdf.SaveAs("output.pdf");
$vbLabelText   $csharpLabel

The ChromePdfRenderer handles all the complexity internally, providing pixel-perfect rendering of your content into a new document. You can also export PDFs to Memory if you need to work with streams instead of files, or load PDFs from memory for processing:

// Save to MemoryStream instead of file
using (var ms = pdf.Stream)
{
    // Use the stream as needed
    byte[] pdfBytes = ms.ToArray();
}
// Save to MemoryStream instead of file
using (var ms = pdf.Stream)
{
    // Use the stream as needed
    byte[] pdfBytes = ms.ToArray();
}
$vbLabelText   $csharpLabel

You can also save PDFs in different formats like PDF/A for archival, PDF/UA for accessibility, or with specific PDF version compatibility:

// Save as PDF/A-3b for long-term archival
pdf.SaveAsPdfA("archived-document.pdf");

// Convert to linearized PDF for fast web viewing
pdf.SaveAsLinearized("web-improve.pdf");
// Save as PDF/A-3b for long-term archival
pdf.SaveAsPdfA("archived-document.pdf");

// Convert to linearized PDF for fast web viewing
pdf.SaveAsLinearized("web-improve.pdf");
$vbLabelText   $csharpLabel

Note: You can add images, new pages, headers, and paragraphs easily in just a few lines, use IronPDF's methods and document object features. The library supports base64 encoding for embedded assets and data URIs for inline images.

How to Convert HTML to PDF Documents?

The real power of IronPDF emerges when generating complex PDF documents. Whether converting HTML to PDF from existing web pages or creating dynamic reports, the HTML-to-PDF conversion maintains complete fidelity. The library supports Bootstrap and Flexbox CSS, SVG graphics, and WebGL content:

// Convert a URL to PDF
var urlPdf = renderer.RenderUrlAsPdf("___PROTECTED_URL_55___");
urlPdf.SaveAs("website.pdf");
// Convert an HTML file with IronPDF's PDF writer
var filePdf = renderer.RenderHtmlFileAsPdf("example-invoice.html");
filePdf.SaveAs("invoice.pdf");
// Use advanced rendering options for your C# PDF generator
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Environment;
renderer.RenderingOptions.MarginTop = 20;
renderer.RenderingOptions.EnableJavaScript = true;
renderer.RenderingOptions.WaitFor.RenderDelay(500); // Wait for dynamic content
// Convert a URL to PDF
var urlPdf = renderer.RenderUrlAsPdf("___PROTECTED_URL_55___");
urlPdf.SaveAs("website.pdf");
// Convert an HTML file with IronPDF's PDF writer
var filePdf = renderer.RenderHtmlFileAsPdf("example-invoice.html");
filePdf.SaveAs("invoice.pdf");
// Use advanced rendering options for your C# PDF generator
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Environment;
renderer.RenderingOptions.MarginTop = 20;
renderer.RenderingOptions.EnableJavaScript = true;
renderer.RenderingOptions.WaitFor.RenderDelay(500); // Wait for dynamic content
$vbLabelText   $csharpLabel

The renderer supports full CSS3, JavaScript execution, and responsive layouts. This ensures your PDFs look exactly as intended. For more details on rendering options, see the IronPDF documentation. You can also convert HTML files, HTML strings, or even HTML ZIP files with equal ease.

For websites requiring authentication, IronPDF supports TLS Website & System Logins and Kerberos authentication. You can add custom HTTP request headers for API access. The JavaScript rendering capabilities ensure dynamic content renders correctly, with custom render delays and JavaScript message listeners for advanced scenarios.

What Does the HTML File Output Look Like?

Split-screen view showing an HTML invoice template code on the left and the generated PDF preview on the right, demonstrating HTML to PDF conversion.

How to Generate Real-World PDF Documents with IronPDF?

Real-world PDF generation in C# often involves dynamic data. Here's how to create a professional invoice using IronPDF's PDF creation API. The code below demonstrates PDF report generation with custom paper sizes and advanced formatting:

string invoiceHtml = $@"
    <html>
    <head>
        <style>
            body {{ font-family: Arial; }}
            .header {{ background: #f0f0f0; padding: 20px; }}
            .total {{ font-weight: bold; font-size: 18px; }}
        </style>
    </head>
    <body>
        <div class='header'>
            <h1>Invoice #{invoiceNumber}</h1>
            <p>Date: {DateTime.Now:yyyy-MM-dd}</p>
        </div>
        <table>
            <tr><td>Product</td><td>Quantity</td><td>Price</td></tr>
            {GenerateLineItems()}
        </table>
        <p class='total'>Total: ${totalAmount:F2}</p>
    </body>
    </html>";
// Use IronPDF's C# PDF writer to create the document
var invoicePdf = renderer.RenderHtmlAsPdf(invoiceHtml);
// Apply digital signature for authenticity
invoicePdf.Sign(new PdfSignature("cert.pfx", "password"));
invoicePdf.SaveAs($"invoice-{invoiceNumber}.pdf");
string invoiceHtml = $@"
    <html>
    <head>
        <style>
            body {{ font-family: Arial; }}
            .header {{ background: #f0f0f0; padding: 20px; }}
            .total {{ font-weight: bold; font-size: 18px; }}
        </style>
    </head>
    <body>
        <div class='header'>
            <h1>Invoice #{invoiceNumber}</h1>
            <p>Date: {DateTime.Now:yyyy-MM-dd}</p>
        </div>
        <table>
            <tr><td>Product</td><td>Quantity</td><td>Price</td></tr>
            {GenerateLineItems()}
        </table>
        <p class='total'>Total: ${totalAmount:F2}</p>
    </body>
    </html>";
// Use IronPDF's C# PDF writer to create the document
var invoicePdf = renderer.RenderHtmlAsPdf(invoiceHtml);
// Apply digital signature for authenticity
invoicePdf.Sign(new PdfSignature("cert.pfx", "password"));
invoicePdf.SaveAs($"invoice-{invoiceNumber}.pdf");
$vbLabelText   $csharpLabel

This approach combines the flexibility of HTML templating with the reliability of PDF output, making it ideal for generating invoices, reports, certificates, and other business documents. Learn more about creating PDF reports in ASP.NET. You can even convert CSHTML to PDF in MVC applications, use Razor Pages for dynamic content generation, or render CSHTML headlessly for server-side processing. For Blazor applications, IronPDF provides smooth integration.

What Does the Generated Invoice Look Like?

Screenshot of a generated PDF invoice displaying Invoice #12345 with a sample product entry and total amount of $250.75

What Advanced Features Improve Your PDFWriter?

IronPDF extends beyond basic PDF creation with enterprise-ready features:

Here's a practical example adding headers with page numbers to your C# PDF documents:

// Configure headers for your .NET PDF writer
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
{
    HtmlFragment = "<div style='text-align:center'>Annual Report 2024</div>",
    MaxHeight = 25
};
// Add page numbers to PDF programmatically
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter()
{
    HtmlFragment = "<div style='text-align:center'>Page {page} of {total-pages}</div>",
    MaxHeight = 20
};
// Add watermark for draft documents
renderer.RenderingOptions.TextHeader = new TextHeaderFooter()
{
    DrawDividerLine = true,
    LeftText = "CONFIDENTIAL",
    RightText = "{date} {time}"
};
// Configure headers for your .NET PDF writer
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
{
    HtmlFragment = "<div style='text-align:center'>Annual Report 2024</div>",
    MaxHeight = 25
};
// Add page numbers to PDF programmatically
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter()
{
    HtmlFragment = "<div style='text-align:center'>Page {page} of {total-pages}</div>",
    MaxHeight = 20
};
// Add watermark for draft documents
renderer.RenderingOptions.TextHeader = new TextHeaderFooter()
{
    DrawDividerLine = true,
    LeftText = "CONFIDENTIAL",
    RightText = "{date} {time}"
};
$vbLabelText   $csharpLabel

For more control over document layout, you can set custom margins, define custom paper sizes, or adjust page orientation. The table of contents feature automatically generates navigation for longer documents. You can also transform PDF pages, draw lines and rectangles, or add text and bitmaps directly to existing PDFs.

When you use this, you can generate PDF files with page numbers in the footer and a custom header. To demonstrate, I'll create a simple multi-page PDF from an HTML string that demonstrate HTML to PDF page breaks and page number formatting:

// Generate long HTML content to create multiple pages for demonstration
// Multi-page HTML with explicit page breaks
string multiPageHtml = "";
for (int i = 1; i <= 5; i++) // 5 pages
{
    multiPageHtml += $@"
            <div style='page-break-after: always;'>
                <h1>Section {i}</h1>
                <p>This is section {i} of the report. Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
                This content will appear on its own page thanks to the CSS page-break.</p>
            </div>";
}
//render HTML string a PDF
var multipagePdf = renderer.RenderHtmlAsPdf(multiPageHtml);
//save PDF
multipagePdf.SaveAs("multiPageReport.pdf");
// Generate long HTML content to create multiple pages for demonstration
// Multi-page HTML with explicit page breaks
string multiPageHtml = "";
for (int i = 1; i <= 5; i++) // 5 pages
{
    multiPageHtml += $@"
            <div style='page-break-after: always;'>
                <h1>Section {i}</h1>
                <p>This is section {i} of the report. Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
                This content will appear on its own page thanks to the CSS page-break.</p>
            </div>";
}
//render HTML string a PDF
var multipagePdf = renderer.RenderHtmlAsPdf(multiPageHtml);
//save PDF
multipagePdf.SaveAs("multiPageReport.pdf");
$vbLabelText   $csharpLabel

Additional features include PDF sanitization for security, flattening PDFs to make forms non-editable, and linearization for fast web viewing. You can also work with PDF DOM objects, scale PDF objects, and translate PDF objects for precise control.

For additional customization, you can stamp text and images, merge or split PDFs, or even extract text and images from existing PDFs. The library also supports UTF-8 and international languages, making it suitable for global applications. For specific formats, you can convert XML to PDF, Markdown to PDF, RTF to PDF, or DOCX to PDF.

How Do Page Numbers Appear in the Final PDF?

PDF viewer showing a two-page spread of 'MultiPageReport.pdf' with Section 1 and Section 2 headers containing Lorem ipsum text, displayed at 75% zoom.

Why Choose IronPDF for Your C# PDF Generation Needs?

IronPDF makes PDF generation in C# straightforward and reliable. You don't need a dedicated PdfWriter class; instead, the renderer and PdfDocument object handle everything from HTML content to page size, headers, and footers. Whether you're creating invoices, reports, or certificates for Microsoft Office integration, IronPDF helps you get the job done in just a few lines of code. The library supports parallel processing for high-volume scenarios and async operations for responsive applications.

With complete documentation, strong support options including engineering support, and a free trial version, getting started is simple. You can experiment with new PDF documents, add images, or adjust font size and page layout without headaches. IronPDF turns PDF creation from a technical chore into a smooth, productive workflow. The library provides demos to demonstrate its capabilities and tutorials for complex scenarios.

The library excels at common tasks like converting images to PDF including multi-frame TIFF support, handling responsive CSS, and supporting web fonts and icons. For debugging, you can debug HTML with Chrome to ensure perfect output. Advanced features include OpenAI integration for intelligent PDF processing, Azure Blob Storage support, and print functionality for physical output.

For deployment, IronPDF provides guides for IIS configuration, ClickOnce deployment, and software installer integration. The library also supports MAUI applications and Android deployment for mobile scenarios.

Get stated with IronPDF now.
green arrow pointer

Ready to modernize your C# PDF writer workflow? Start your free trial and experience how IronPDF simplifies PDF creation in .NET. With complete documentation, API reference, and responsive support, you'll be generating professional PDFs in minutes, not hours. Check our changelog for the latest updates and milestones for upcoming features.

Transform your document creation today with IronPDF and join thousands of developers who've already switched to modern PDF generation in C#. Whether you're using VB.NET, F#, or working with Blazor, IronPDF has you covered.

Frequently Asked Questions

What is C# PDFWriter?

C# PDFWriter is a tool that allows developers to create PDF documents programmatically using the C# programming language.

Why should developers choose C# PDFWriter?

Developers should choose C# PDFWriter because it simplifies the process of creating PDFs, reducing the need for complex APIs and boilerplate code.

How does IronPDF enhance PDF creation in C#?

IronPDF provides a streamlined API that makes it easier for developers to generate, manipulate, and customize PDF documents directly within their C# applications.

What challenges do older open source libraries present?

Older open source libraries often have complex APIs and require extensive boilerplate code, making PDF creation cumbersome and time-consuming.

Can IronPDF handle complex PDF creation tasks?

Yes, IronPDF is designed to handle both simple and complex PDF creation tasks efficiently, offering numerous features for customization and automation.

What are the benefits of using IronPDF over other PDF libraries?

IronPDF offers a user-friendly API, comprehensive documentation, and robust features that reduce development time and enhance the quality of PDF outputs.

Is IronPDF suitable for beginners in C# development?

Yes, IronPDF is suitable for beginners as it simplifies PDF creation with straightforward code examples and extensive support resources.

How does IronPDF integrate with .NET applications?

IronPDF integrates seamlessly with .NET applications, allowing developers to incorporate PDF functionalities directly within their projects using C#.

What kind of support is available for developers using IronPDF?

Developers using IronPDF have access to comprehensive documentation, community forums, and technical support to assist with any development challenges.

Can IronPDF be used for both web and desktop applications?

Yes, IronPDF can be used for both web and desktop applications, offering flexibility in how PDFs are generated and managed across different platforms.

Does IronPDF support the latest .NET 10 version?

Yes, IronPDF fully supports .NET 10, along with .NET 9, .NET 8, .NET 7, .NET 6, .NET Core, and .NET Framework, enabling developers to use the C# PDFWriter and related APIs in modern .NET 10 applications.

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