DEV Community

Cover image for How to Create a Pdf File in C#
Mehr Muhammad Hamza
Mehr Muhammad Hamza

Posted on • Edited on

How to Create a Pdf File in C#

PDF generation is a crucial task in modern software applications, enabling document automation, reporting, and data archiving to name a few tasks. Whether you're converting HTML, Word Documents, or structured data formats like XML and JSON, the C# environment offers a variety of tools and libraries, such as IronPDF, to streamline the process.

If you're a developer looking for a tool to help you handle HTML to PDF tasks, carry out various PDF generation tasks, work with PDF reports, invoice documents, and more, then be sure to read on. In this article we will walk you through the best techniques, libraries, and practical implementations for converting different file formats to PDF files using C#.

Setting Up Your C# Environment for PDF Generation

Before diving into how C# creates PDF files, you first need to ensure that your deployment environment is properly configured. By setting up your environment correctly, you can prevent any compatibility issues and allow for smoother integration of different libraries for PDF generation.

Choosing the Right .NET Version

Ensure you have an up-to-date .NET environment installed. C# PDF libraries often support multiple versions of .NET, including .NET 6, .NET 7, and .NET 8. You can check which .NET SDK versions are installed on your system using the following command:

dotnet --list-sdks
Enter fullscreen mode Exit fullscreen mode

Or, you can check what .NET runtimes are currently installed with the following command:

dotnet --list-runtimes
Enter fullscreen mode Exit fullscreen mode

If you don’t have the required version, download and install it from Microsoft's .NET website. Using the latest version ensures access to performance improvements, security patches, and better compatibility with third-party libraries.

Creating a C# Project

Once the correct .NET version is installed, create a new project based on your project type and needs:

  • Console Application: Suitable for scripts and automation tasks.
  • ASP.NET Core Web API: Ideal for generating PDFs dynamically in web apps.
  • Windows Forms/WPF: Best for GUI-based applications needing PDF export.

To create a new project in Visual Studio, first you need to choose to create a new project. Then, select the template that best fits your need. For example, here we have chosen a Console Application.

Project Templates Screen - Visual Studio

Now, we can name our project and choose its file location.

Project Creation - Naming the project and choosing the file location

Finally, choose your .NET Framework, and click "Create".

Choosing the .NET Framework for our project

Of course, these creation steps may vary depending on the project type chosen.

Installing PDF Libraries via NuGet Package Manager

The NuGet package manager for .NET allows for easy installation of PDF libraries. After choosing the .NET PDF library/libraries that best fits your needs, you can then easily install them via the NuGet package manager console.

For example:

// Install IronPDF for HTML-to-PDF rendering and automation
Install-Package IronPdf

// Install PdfSharp for lightweight PDF creation
Install-Package PDFsharp

// Install Aspose.PDF for enterprise-grade document processing
Install-Package Aspose.PDF 
Enter fullscreen mode Exit fullscreen mode

Verifying Installation with a Simple PDF

To confirm that your environment is correctly set up, create a simple PDF using IronPDF:

using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();

PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello World!");

pdf.SaveAs("output.pdf");
Enter fullscreen mode Exit fullscreen mode

Simple PDF output

If this executes without errors and generates the correct PDF document, then your setup is complete. Ensure you have the correct license key displayed if the library's license type requires if for use. IronPDF offers a free trial for those looking to try it out before they buy.

Conversion-Based PDF Creation Cookbook

Now let's dive into the heart of the cookbook: the various conversion techniques. We'll cover step-by-step guides for converting several common file types into PDF files by looking at different code snippets, as well as performance considerations and troubleshooting tips.

Convert XML to PDF

Use Case: XML is widely used for structured data representation in various industries, including finance, healthcare, and e-commerce. Converting XML to PDF allows for easy report generation and archiving.

Best library choices:

  • Aspose.PDF: Best for handling complex XML structures and large datasets.
  • IronPDF: Useful for quick transformations via XSLT templates.

Code Example: Using Aspose.PDF for XML to PDF

Aspose.PDF provides a direct way to convert XML content into a PDF document.

using Aspose.Pdf;
using System.IO;

string xmlFilePath = "xmlExample.xml";

// Creating a new document object
using var document = new Aspose.Pdf.Document();

document.BindXml(xmlFilePath );
document.Save("aspose-output.pdf");
Enter fullscreen mode Exit fullscreen mode

Output

The Input XML content vs. the output PDF

Code Example: Using XSLT with IronPDF

If your XML data follows a structured format, you can use XSLT to transform XML into HTML before converting it to PDF.

using IronPdf;
using System.Xml;
using System.Xml.Xsl;

var xslt = "exampleXslt.xsl";
var xml = "exampleXml.xml";

XslCompiledTransform transform = new XslCompiledTransform();
using (XmlReader reader = XmlReader.Create(new StringReader(xslt)))
{
    transform.Load(reader);
}
StringWriter results = new StringWriter();
using (XmlReader reader = XmlReader.Create(new StringReader(xml)))
{
    transform.Transform(reader, null, results);
}
IronPdf.ChromePdfRenderer Renderer = new IronPdf.ChromePdfRenderer();
// options, headers and footers may be set there
// Render our XML as a PDF via XSLT
Renderer.RenderHtmlAsPdf(results.ToString()).SaveAs("IronPdf-output.pdf");
Enter fullscreen mode Exit fullscreen mode

Output

IronPDF XML to PDF output

Handling Large XML Files

When working with large XML files, its important to keep in mind a few troubleshooting steps to ensure efficient file processing while avoiding any errors.

For very large XML files, consider using streaming techniques to handle memory more efficiently. While working with these large XML files, be sure to that you keep the process as streamlined as possible, avoid any unnecessary object creation while your program is processing the XML files. Handling large XML files can result in memory issues or slow performance. To mitigate this, consider using streaming methods or break large files into smaller chunks.

Library Selection Guide

So, which library here would be best for your XML to PDF projects?

  • IronPDF: Best for quick, simple XML to PDF conversion with minimal setup.
  • Aspose.PDF: Best for handling complex XML structures and large datasets.

Convert Word (DOCX) to PDF

Use Case: Microsoft Word documents are a commonly used for a variety of document types, such as letters, reports, resumes, invoices, and more. Through converting these documents into PDF format, you are not only preserving the formatting of your Word documents, but are also creating an easy to share, universally compatible, document.

Best library choices:

  • IronPDF: IronPDF's DocxToPdfRenderer provides a powerful method for converting Word documents to PDF in just a few lines of code. Couple this with IronWord's capability for creating Word documents programmatically and it makes a powerful duo.
  • Aspose.Words: A robust library designed for complex Word document handling, including conversion, manipulation, and formatting preservation.

Code Example: Converting DOCX to PDF with IronWord

using IronPdf;

DocxToPdfRenderer renderer = new DocxToPdfRenderer();

// Passing the file name for the DOCX file we want to convert
PdfDocument doc = renderer.RenderDocxAsPdf("document.docx");

doc.SaveAs("docx-to-pdf.pdf");
Enter fullscreen mode Exit fullscreen mode

Output

IronPDF DOCX to PDF output
Library Selection Guide:

The right library for your DOCX to PDF needs solely relies on your project's needs, your budget, and which API you're most comfortable with. However, below we have outlined which library best fits which general needs:

  • IronPDF: Best for quick, simple Word-to-PDF conversion with minimal setup.
  • Aspose.PDF: Best for handling complex Word formatting and large documents.

Convert RTF to PDF

Use Case: Rich Text Format (RTF) files are often used for documents with basic formatting. Converting these files into PDFs can help preserve the structure while making them easily shareable and printable.

Libraries Used:

  • Aspose.Words: Aspose.Words is ideal for RTF-to-PDF conversion, as it provides strong support for complex formatting such as tables, fonts, and styles.
  • IronPDF: IronPDF offers a simple API for converting RTF files to PDF, making it an excellent choice for straightforward tasks.

Code Example: Converting RTF to PDF with IronPDF

using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();

var rtf = "Report.rtf";

PdfDocument pdf = renderer.RenderRtfFileAsPdf(rtf);

pdf.SaveAs("rtf-to-pdf.pdf");
Enter fullscreen mode Exit fullscreen mode

Output

IronPDF RTF to PDF
Library Selection Guide:

  • Aspose.Words: Best for handling complex RTF documents, especially those with tables, complex formatting, and multimedia.
  • IronPDF: Suitable for straightforward RTF-to-PDF conversions with simple formatting.

Convert Markdown to PDF

Use Case: Markdown is commonly used for writing documentation, blog posts, and articles. Converting Markdown to PDF provides a formatted, print-ready version of these files.

Best library choices:

  • Markdig: Markdig is a powerful .NET Markdown processor that converts Markdown to HTML, which can then be converted into PDF using a library like IronPDF.
  • IronPDF: Once the Markdown is converted to HTML, IronPDF can handle the conversion to PDF with great results.

Code Example: Converting Markdown to PDF with IronPDF and Markdig

using IronPdf;
using Markdig;

string markdown = "# Hello World\n This is a **Markdown** file."; 
string htmlContent = Markdown.ToHtml(markdown);

ChromePdfRenderer renderer = new ChromePdfRenderer();   
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);

pdf.SaveAs("markdown.pdf");
Enter fullscreen mode Exit fullscreen mode

Output

Simple PDF
Library Selection Guide:

  • Markdig + IronPDF: Best for converting Markdown to PDF, especially when you need precise control over the HTML-to-PDF rendering process.
  • IronPDF: Best for scenarios where you need the PDF to match the original Markdown document’s formatting exactly.

Convert HTML to PDF

Use Case: Converting HTML to PDF is ideal for generating printable versions of web pages, reports, and invoices. The ability to preserve styling and dynamic content is key, and with IronPDF, you can easily generate PDF documents from CSS-heavy webpages, structured HTML files, or even just simple HTML string.

Best library choices:

  • IronPDF: IronPDF supports high-fidelity HTML to PDF conversion, including full support for modern web technologies like CSS, JavaScript, and media queries. It renders HTML content into a polished PDF document.
  • wkhtmltopdf: A lightweight, open-source solution for HTML to PDF conversion. It uses the WebKit engine and is useful for simple HTML conversion tasks but may struggle with dynamic content or JavaScript-heavy pages.

Code Example: Converting a Webpage to PDF with IronPDF

using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.EnableJavaScript = true;
renderer.RenderingOptions.WaitFor.JavaScript(5000);
renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;
PdfDocument pdf = renderer.RenderUrlAsPdf("https://apple.com");

pdf.SaveAs("webpage.pdf");
Enter fullscreen mode Exit fullscreen mode

Output

Webpage to PDF output

This screenshot shows how IronPDF can handle CSS-intensive HTML web content while maintaining the original layout and quality.

Library Selection Guide:

  • IronPDF: Best for high-fidelity HTML-to-PDF conversion with complex styling and JavaScript content.
  • wkhtmltopdf: Ideal for simple, static HTML pages without heavy dynamic content.

Convert CSV to PDF Files

Use Case: When working with data for reports, the ability to convert tabular data from CSV files to PDF can be an invaluable tool.

Best Library Choices:

  • IronPDF: Great for CSV to PDF conversion.
  • IronXL: A great tool for working with CSV files.

Code Example: Converting a CSV file to PDF file with IronPDF

using IronPdf;
using IronXL;

var workbook = WorkBook.LoadCSV("data.csv");
workbook.ExportToHtml("temp.html");

var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlFileAsPdf("temp.html");

pdf.SaveAs("data.pdf");
Enter fullscreen mode Exit fullscreen mode

Output

CSV to PDF Output

Generating PDF documents from Templates in C#

Generating PDFs from templates is a powerful way to automate document creation, ensuring consistency and efficiency. Whether you’re creating invoices, reports, contracts, or structured data exports, C# offers multiple ways to generate PDFs from different template formats.

Convert HTML Templates to PDF

Use Case: HTML templates provide a flexible way to design structured documents. Businesses use them for invoices, reports, receipts, and other printable formats. By dynamically injecting data into an HTML template, you can generate polished PDF files for record-keeping or distribution

Best Library Choices:

  • IronPDF: This robust library is perfect for HTML template rendering, thanks to its comprehensive support for CSS, JavaScript, and embedded assets.

Code Example: Rendering an HTML Template with Dynamic Data

1. Create an HTML Template (invoice_template.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Invoice</title>
    <style>
        body { font-family: Arial, sans-serif; }
        .invoice { width: 600px; margin: auto; border: 1px solid #ddd; padding: 20px; }
        .header { text-align: center; font-size: 20px; font-weight: bold; }
        .details { margin-top: 20px; }
        .footer { margin-top: 30px; font-size: 14px; text-align: center; }
    </style>
</head>
<body>
    <div class="invoice">
        <div class="header">Invoice #{{InvoiceNumber}}</div>
        <div class="details">
            <p><strong>Customer:</strong> {{CustomerName}}</p>
            <p><strong>Total Amount:</strong> ${{TotalAmount}}</p>
            <p><strong>Date:</strong> {{InvoiceDate}}</p>
        </div>
        <div class="footer">Thank you for your business!</div>
    </div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

2. C# Code to Populate and Convert the Template to PDF

using IronPdf;

string templatePath = "htmlTemplate.html";
string htmlContent = File.ReadAllText(templatePath);

htmlContent = htmlContent.Replace("{{InvoiceNumber}}", "12345")
                                 .Replace("{{CustomerName}}", "John Doe")
                                 .Replace("{{TotalAmount}}", "250.00")
                                 .Replace("{{InvoiceDate}}", "March 25, 2025");

var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(htmlContent);

pdf.SaveAs("htmlTemplate.pdf");
Enter fullscreen mode Exit fullscreen mode

Output

Output for HTML template to PDF

Performance Considerations

  • Ensure external CSS files and fonts are properly linked if not inline.
  • Large HTML files with high-resolution images may require additional memory.
  • JavaScript execution should be tested to ensure proper rendering.

Troubleshooting: Missing Assets

  • Use absolute paths or embed styles inline to prevent missing CSS.
  • Ensure fonts are embedded or linked correctly.
  • Verify that JavaScript content executes before rendering the PDF.

Library Selection Guide

  • IronPDF: Best for dynamic HTML rendering with full CSS and JavaScript support.
  • wkhtmltopdf: Lightweight alternative, but lacks modern CSS compatibility.

Convert PowerPoint Templates (PPTX) to PDF

Use Case: Generating PDFs from PowerPoint templates with placeholders for slides.

Best Library Choices

  • Aspose.Slides – Advanced PowerPoint processing with animations.
  • Spire.Presentation – Lightweight alternative for basic slide conversion.

Code Example: Replacing Text in a PowerPoint Template and Converting it to a PDF

using Spire.Presentation;

var presentation = new Presentation();
presentation.LoadFromFile("Example.pptx");

// Loop through slides and replace placeholders
foreach (ISlide slide in presentation.Slides)
{
    foreach (IShape shape in slide.Shapes)
    {
        if (shape is IAutoShape autoShape && autoShape.TextFrame != null)
        {
            autoShape.TextFrame.Text = autoShape.TextFrame.Text.Replace("{{Placeholder}}", "Dynamic Content");
        }
    }
}

// Save as PDF
presentation.SaveToFile("presentation.pdf", Spire.Presentation.FileFormat.PDF);
Enter fullscreen mode Exit fullscreen mode

Output

PPTX Template to PDF output

Performance Considerations

  • Ensure slide formatting, images, and embedded fonts are retained.
  • Animations and transitions will not be preserved in the PDF output.

Troubleshooting

  • Text misalignment – Adjust layout settings before conversion.
  • Missing images – Ensure embedded media is properly referenced.

Library Selection Guide

  • Aspose.Slides – Best for preserving animations and complex slide layouts.
  • Spire.Presentation – A lightweight, free alternative for basic slide-to-PDF conversion.

Convert Excel Templates (XLSX/CSV) to PDF

Use Case: Creating financial reports, budget summaries, and structured tables as PDFs.

Best Library Choices:

  • IronXL – Simple Excel-to-PDF conversion.
  • Aspose.Cells – Advanced Excel processing with full formatting support.

Code Example: Filling an Excel Template and Exporting to PDF

using IronXL;
using IronPdf;

var workbook = WorkBook.Load("template.xlsx");
var sheet = workbook.DefaultWorkSheet;
sheet["B11"].Value = "Outgoing";
sheet["C11"].Value = "1800";

workbook.Save();

//Export it to HTML
workbook.ExportToHtml("invoice.html");

// Convert the HTML to PDF using IronPDF
ChromePdfRenderer renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlFileAsPdf("invoice.html");
pdf.SaveAs("invoice_1.pdf");
Enter fullscreen mode Exit fullscreen mode

Output

Before and After Excel template to PDF converter

Performance Considerations

  • Large spreadsheets may need pagination control.
  • Formulas should be pre-calculated before conversion.

Troubleshooting

  • Row/column overflow – Adjust cell wrapping and layout.

Library Selection Guide

  • IronXL – Best for simple Excel-to-PDF needs.
  • Aspose.Cells – Best for complex spreadsheet formatting.

Convert Markdown Templates to PDF

Use Case: Some situations where it could be handy to fill out template markdown files and convert them to PDF include generating developer documentation and knowledge base articles.

Best Library Choices:

  • Markdig – Markdown processing.
  • IronPDF – Converts Markdown output to PDF.

Code Example: Converting a Markdown Template to PDF

using IronPdf;

var markdown = "template.md";

ChromePdfRenderer renderer = new ChromePdfRenderer();
var pdf = renderer.RenderMarkdownFileAsPdf(markdown);

pdf.ReplaceTextOnAllPages("{Topic}", "Sample Software");
pdf.ReplaceTextOnAllPages("{Header}", "Installation");
pdf.ReplaceTextOnAllPages("{Date}", DateTime.Now.ToString("dd-mm-yyyy"));

pdf.SaveAs("test.pdf");
Enter fullscreen mode Exit fullscreen mode

Output

Markdown Template to PDF

Performance Considerations

  • Ensure code blocks and tables are properly styled.

Troubleshooting

  • Loss of formatting – Use CSS to enhance styling.

Library Selection Guide

  • IronPDF – Best for styled Markdown-to-PDF conversion.

Convert JSON Templates to PDF

Use Case: Creating structured reports like invoices and analytics from JSON data.

Best Library Choices:

  • Newtonsoft.Json – JSON parsing.
  • IronPDF – Rendering structured data into PDFs.

Code Example: Generating a PDF from JSON Template

using IronPdf;
using Newtonsoft.Json;

// Load the JSON template
string templatePath = "template.json";
string jsonTemplate = File.ReadAllText(templatePath);

// Replace placeholders with actual data
string populatedJson = jsonTemplate
    .Replace("{{InvoiceNumber}}", "INV-2025001")
    .Replace("{{Date}}", DateTime.Now.ToShortDateString())
    .Replace("{{CustomerName}}", "John Doe")
    .Replace("{{CustomerEmail}}", "johndoe@example.com")
    .Replace("{{CustomerAddress}}", "123 Main Street, New York, NY 10001")
    .Replace("{{Item1Description}}", "Web Development Services")
    .Replace("{{Item1Quantity}}", "1")
    .Replace("{{Item1UnitPrice}}", "1500.00")
    .Replace("{{Item1Total}}", "1500.00")
    .Replace("{{Item2Description}}", "Hosting (12 months)")
    .Replace("{{Item2Quantity}}", "1")
    .Replace("{{Item2UnitPrice}}", "200.00")
    .Replace("{{Item2Total}}", "200.00")
    .Replace("{{Subtotal}}", "1700.00")
    .Replace("{{Tax}}", "85.00")
    .Replace("{{TotalAmount}}", "1785.00")
    .Replace("{{Notes}}", "Payment due within 30 days. Thank you for your business!");

// Convert JSON into HTML for PDF generation
string htmlContent = GenerateHtmlFromJson(populatedJson);

// Convert HTML to PDF using IronPDF
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(htmlContent);

// Save the PDF
pdf.SaveAs("Invoice.pdf");

static string GenerateHtmlFromJson(string jsonData)
{
    dynamic data = JsonConvert.DeserializeObject(jsonData);

    return $@"
        <html>
        <head>
            <style>
                body {{ font-family: Arial, sans-serif; }}
                table {{ width: 100%; border-collapse: collapse; margin-top: 20px; }}
                th, td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}
                th {{ background-color: #f4f4f4; }}
            </style>
        </head>
        <body>
            <h2>Invoice #{data.InvoiceNumber}</h2>
            <p><strong>Date:</strong> {data.Date}</p>
            <p><strong>Customer:</strong> {data.Customer.Name}</p>
            <p><strong>Email:</strong> {data.Customer.Email}</p>
            <p><strong>Address:</strong> {data.Customer.Address}</p>

            <h3>Items</h3>
            <table>
                <tr>
                    <th>Description</th>
                    <th>Quantity</th>
                    <th>Unit Price</th>
                    <th>Total</th>
                </tr>
                <tr>
                    <td>{data.Items[0].Description}</td>
                    <td>{data.Items[0].Quantity}</td>
                    <td>${data.Items[0].UnitPrice}</td>
                    <td>${data.Items[0].Total}</td>
                </tr>
                <tr>
                    <td>{data.Items[1].Description}</td>
                    <td>{data.Items[1].Quantity}</td>
                    <td>${data.Items[1].UnitPrice}</td>
                    <td>${data.Items[1].Total}</td>
                </tr>
            </table>

            <h3>Summary</h3>
            <p><strong>Subtotal:</strong> ${data.Subtotal}</p>
            <p><strong>Tax:</strong> ${data.Tax}</p>
            <p><strong>Total Amount:</strong> ${data.TotalAmount}</p>
            <p><em>{data.Notes}</em></p>
        </body>
        </html>";
}
Enter fullscreen mode Exit fullscreen mode

Output

JSON template to PDF example

Advanced PDF Handling in C#

Working with PDFs in C# goes beyond simple file generation—it involves handling byte arrays, streams, images, and web content, as well as optimizing performance for large-scale applications. Whether you're converting dynamic webpages, embedding images, or generating PDF files without external dependencies. In this section, we'll be taking a closer look at how you can handle advanced PDF tasks.

Convert Byte Array to PDF

Use Case: This approach is often used for generating PDF files from in-memory data. In-memory PDF generation is useful when dealing with byte arrays retrieved from databases, file uploads, or API responses. This approach is common in applications that store PDF files as blobs and need to regenerate them dynamically.

Code Example: Creating PDF files from a Byte Array with IronPDF

using IronPdf;

byte[] pdfBytes = new ChromePdfRenderer().RenderHtmlAsPdf("<h1>Hello, PDF!</h1>").BinaryData;

// Convert byte array back to a PDF file
File.WriteAllBytes("output.pdf", pdfBytes);
Enter fullscreen mode Exit fullscreen mode

Output

Byte Array to PDF output

Troubleshooting: Managing Memory Usage

  • Use memory streams efficiently: If you need to work with the PDF without saving it, wrap the byte array in a MemoryStream.
  • Optimize byte array handling: If PDF files are large, consider using compression features within IronPDF to reduce file size.
  • Streaming instead of storing: Instead of saving to disk, stream the byte array directly to the client in a web application.

Example: Returning a PDF as a byte array in an ASP.NET API:

[HttpGet("generate-pdf")]
public IActionResult GeneratePdf()
{
    var pdf = new HtmlToPdf().RenderHtmlAsPdf("<h1>Dynamic PDF</h1>");
    return File(pdf.BinaryData, "application/pdf", "download.pdf");
}
Enter fullscreen mode Exit fullscreen mode

This method prevents excessive disk writes and allows for efficient PDF delivery in web applications.

Convert Stream to PDF

Use Case: When working with web applications, handling PDF files as streams allows for efficient processing without writing temporary files. This is particularly useful for APIs that generate and serve PDF files on demand.

Code Example: Creating a PDF file from a Stream

using IronPdf;

var renderer = new ChromePdfRenderer();

byte[] pdfBytes = renderer.RenderHtmlAsPdf("<h1>Hello, PDF!</h1><p>PDF generated using IronPDF via a Stream</p>").BinaryData;

using (MemoryStream stream = new MemoryStream(pdfBytes))
{
    File.WriteAllBytes("output.pdf", stream.ToArray());
}
Enter fullscreen mode Exit fullscreen mode

Output

PDF generated from a stream

Why use a stream?

  • Avoids file system access, improving performance.
  • Works seamlessly in cloud-based and API-driven applications.
  • Ideal for streaming PDFs directly to the client in ASP.NET.

Convert Images to PDF and Vice Versa

Use Case: Archiving Images into PDFs and Extracting Images from PDF images and pages. Businesses often need to archive scanned documents or convert images into PDFs for better storage and organization. On the flip side, extracting images from PDFs is useful for retrieving embedded graphics.

Best Library Choices:

  • IronPDF: Best for quick and simple image-to-PDF conversion.
  • PdfSharp: Best for more customizable image handling.

Code Example: Converting Images to a Multi-Paged PDF File

using IronPdf;

var pdf = ImageToPdfConverter.ImageToPdf("example.png");

pdf.SaveAs("imageToPdf.pdf");
Enter fullscreen mode Exit fullscreen mode

Output

Images to PDF output

Code Example: PDF to Image

using IronPdf;

var pdf = PdfDocument.FromFile("Input_File.pdf");

pdf.RasterizeToImageFiles("example_image.png");
Enter fullscreen mode Exit fullscreen mode

Output

PDF to image output

Converting Webpages to PDF Files in C#

Web content is increasingly complex, featuring JavaScript, CSS, and dynamic elements. Converting webpages to PDFs requires handling these elements properly.

Library Selection Guide

  • IronPDF – Best for web content that includes JavaScript and CSS.
  • wkhtmltopdf – Good for static HTML-to-PDF needs.

Convert Razor Pages to PDF

Use Case: Exporting dynamic MVC views. If your application uses Razor Pages, converting them to PDFs allows for downloadable reports, invoices, or receipts.

Code Example: Rendering a Razor Page as a PDF File

using IronPdf.Razor.Pages;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using SampleProject.Models;

namespace RazorPageSample.Pages
{
    public class PersonsModel : PageModel
    {
        [BindProperty(SupportsGet = true)]
        public List<Person> persons { get; set; }

        public void OnGet()
        {
            persons = new List<Person>
            {
            new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
            new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
            new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
            };

            ViewData["personList"] = persons;
        }
        public IActionResult OnPostAsync()
        {
            persons = new List<Person>
            {
            new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
            new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
            new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
            };

            ViewData["personList"] = persons;

            ChromePdfRenderer renderer = new ChromePdfRenderer();

            // Render Razor Page to PDF document
            PdfDocument pdf = renderer.RenderRazorToPdf(this);

            Response.Headers.Add("Content-Disposition", "inline");

            return File(pdf.BinaryData, "application/pdf", "razorPageToPdf.pdf");

            // View output PDF on browser
            return File(pdf.BinaryData, "application/pdf");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Razor page to PDF output

Convert CSHTML to PDF

Use Case: Generating PDFs from ASP.NET Core Views. CSHTML pages in ASP.NET Core often contain dynamic content that needs to be accurately converted to PDF format.

Code Example: Converting a CSHTML File to PDF

using IronPdf;
using Sample.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Sample.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        // GET: Person
        public ActionResult Persons()
        {
            var persons = new List<Person>
            {
            new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
            new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
            new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
            };
            if (HttpContext.Request.HttpMethod == "POST")
            {
                // Provide the path to your View file
                var viewPath = "~/Views/Home/Persons.cshtml";
                ChromePdfRenderer renderer = new ChromePdfRenderer();
                // Render View to PDF document
                PdfDocument pdf = renderer.RenderView(this.HttpContext, viewPath, persons);
                Response.Headers.Add("Content-Disposition", "inline");
                // View the PDF
                return File(pdf.BinaryData, "application/pdf");
            }
            return View(persons);
        }
        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";
            return View();
        }
        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";
            return View();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

CSHTML to PDF output

Convert ASPX Pages to PDF

Use Case: Saving Classic ASP.NET WebForms Pages as PDFs. If you’re still working with legacy WebForms (ASPX), you can generate PDFs from these pages dynamically.

Code Example: Converting an ASPX Webpage to a PDF File

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AspxToPdf
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {IronPdf.AspxToPdf.RenderThisPageAsPdf(IronPdf.AspxToPdf.FileBehavior.InBrowser);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

ASPX webpage to PDF output

Creating PDFs in C# Without External Libraries

Use Case: In some scenarios, using external libraries like IronPDF, PdfSharp, or QuestPDF may not be an option. This is often due to security policies, licensing costs, or the need to keep dependencies minimal. If your project has such restrictions, you may need to generate PDFs using only the built-in capabilities of .NET.

However, it’s important to note that .NET does not provide a native PDF-generation library. Instead, you must work with graphical libraries such as System.Drawing or Windows.Media (for WPF applications) to create PDF-like content. The workaround often involves drawing text and images onto an image file and then saving it in a format compatible with PDF tools.

Code Example: Using System.IO and System.Drawing in .NET

using System;
using System.IO;
using System.Drawing;
using System.Drawing.Printing;

PrintDocument doc = new PrintDocument();
doc.PrintPage += (sender, e) =>
{
    e.Graphics.DrawString("This PDF was generated using System.IO!", new Font("Arial", 12), Brushes.Black, 50, 50);
};
doc.Print();
Enter fullscreen mode Exit fullscreen mode

Output

PDF generated using System.IO and System.Drawing

Why This Approach Has Limitations

  • No true PDF support – The output is an image file, not a real PDF.
  • No text selection – Since the content is drawn as an image, text cannot be copied or searched.
  • No vector graphics support – You are limited to bitmap-based rendering, which is not ideal for professional documents.

More PDF Conversions in C#

Beyond standard PDF creation, many applications require conversion from other formats. Whether you're generating PDFs from structured data, email formats, or scientific documents, C# offers various ways to handle these conversions.

Convert YAML to PDF in C#

YAML files store structured data commonly used in configuration files. If you need to generate a PDF from YAML:

  • Use Case: Converting YAML configuration files into readable reports.
  • Approach: Parse YAML with YamlDotNet and format the content as a PDF.
  • Example Library: IronPDF, QuestPDF.

Convert Database Query Results to PDF in C#

Database query results often need to be exported as PDFs for reporting.

  • Use Case: Generating invoices, financial reports, or analytics dashboards.
  • Approach: Retrieve SQL query results, format as an HTML table, and convert to a PDF.
  • Example Library: IronPDF, FastReports.NET.

Convert LaTeX to PDF in C#

LaTeX is commonly used in academic and scientific publishing.

  • Use Case: Generating research papers, mathematical documents, or books.
  • Approach: Call an external LaTeX processor like pdflatex from C# code.
  • Example Library: PdfLaTeX command-line integration.

Convert Email (EML/MSG) to PDF in C#

Emails often contain important information that needs archiving in a non-editable format.

  • Use Case: Legal documentation, email archiving, or compliance reports.
  • Approach: Extract email contents and format them as a structured PDF.
  • Example Library: Aspose.Email, MailKit.

Performance and Optimization Tips

When working with large PDFs or generating a high volume of documents, efficiency becomes a priority. Poorly optimized code can lead to excessive memory usage, slow processing times, or even crashes. Below are some best practices for ensuring your PDF-handling code is performant.

Handling Large Documents Efficiently

Processing large PDFs—such as legal contracts, books, or scanned archives—requires strategic memory management.

  • Lazy Loading – If processing an existing PDF, load only the pages you need rather than the entire document.
  • Batch Processing – When merging multiple PDFs, process them in smaller chunks to avoid high memory consumption.
  • Stream-Based Processing – Use streams instead of storing entire PDFs in memory to reduce RAM usage.

Best Practices for Multi-Threaded PDF Generation

Generating PDFs in a multi-threaded environment improves speed but introduces concurrency challenges.

Use async/await to Prevent Blocking
When working in an ASP.NET environment, avoid synchronous operations that block the request thread:

var pdf = await Task.Run(() => new ChromePdfRenderer().RenderHtmlAsPdf("<h1>Async PDF</h1>"));
await pdf.SaveAsAsync("async-output.pdf");
Enter fullscreen mode Exit fullscreen mode

Process PDFs in Parallel
If generating multiple PDFs, use Parallel.ForEach to distribute the workload across multiple threads:

Parallel.ForEach(filePaths, filePath =>
{
    var pdf = new ChromePdfRenderer().RenderHtmlAsPdf(File.ReadAllText(filePath));
    pdf.SaveAs(Path.ChangeExtension(filePath, ".pdf"));
});
Enter fullscreen mode Exit fullscreen mode

Memory Management Strategies

When working with high-resolution images or large documents, improper memory usage can lead to performance issues.

Dispose of Objects Explicitly
Many PDF libraries generate large objects that should be disposed of immediately after use:

using (var pdf = new ChromePdfRenderer().RenderHtmlAsPdf("<h1>Optimized PDF</h1>"))
{
    pdf.SaveAs("output.pdf");
}
Enter fullscreen mode Exit fullscreen mode

Enable Compression to Reduce File Size
If your PDFs contain many images, consider compressing them before saving:

var pdf = new ChromePdfRenderer().RenderHtmlAsPdf("<h1>Compressed PDF</h1>");
pdf.CompressImages(50); // Reduces image quality but saves space
pdf.SaveAs("compressed.pdf");
Enter fullscreen mode Exit fullscreen mode

Conclusion

Congratulations! You've now got a comprehensive toolkit for all your PDF creation and conversion needs in C#. From simple "Hello, World!" PDF files to complex reports, spreadsheets, and presentations, this guide has covered the essential methods and libraries to turn your C# projects into PDF powerhouses. Libraries such as IronPDF make working with new or existing PDF documents a breeze.

Whether you're working with IronPDF for easy HTML-to-PDF conversions, Aspose.PDF for more advanced document processing, or IronXL for handling Excel data, you now know which library suits your task best. We've also dived into creating PDFs from scratch using System.IO and System.Drawing — perfect for when you need a simple solution without third-party dependencies.

And let’s not forget about web-based PDF files. With IronPDF, converting web pages, Razor Pages, and even complex HTML is a breeze, while the tips and tricks we’ve discussed ensure that your PDFs not only look great but also perform efficiently, even with large files.

If you're diving deeper into Markdown, LaTeX, or JSON-to-PDF conversions, this guide has pointed you toward the right tools, ensuring a seamless process for all your specialized needs. For those on a tighter budget, there are plenty of open-source library options out there.

Keep exploring and optimizing!

  • IronPDF Documentation for even more advanced features, complete code examples, and tips.
  • Dive into the IronXL documentation to learn how you can take your Excel reports to the next level.
  • Take a look at how IronWord's various features can be utilized to create amazing Word documents. without the need for Microsoft office interop.
  • Try out the IronPDF, IronWord, and IronXL free trials to explore these powerful libraries for yourself.

No matter the type of content you’re converting, you now have a solid foundation and the resources to make PDF generation in C# as smooth and efficient as possible. Get started today and elevate your C# projects with seamless PDF workflows!

Top comments (2)

Collapse
 
jaackhowlett profile image
Jack Howlett • Edited

Hi, I suggest trying ZetPDF for this!zetpdf.com/

Collapse
 
jackhowlett profile image
Hunzla

If you're looking for a reliable solution to generate PDF files in C#, you should check out ZetPDF. It’s a great SDK for .NET and allows you to create PDFs from scratch.