DEV Community

Simran Kohli
Simran Kohli

Posted on

How to Convert XML to PDF in C# (.NET Guide)

Converting XML files into well-formatted PDF documents is a common requirement in many software applications. Whether it’s invoices, reports, data exports, or printable forms, XML acts as a flexible data representation format, while PDF serves as the go-to format for distribution and printing. In this article, we will walk you through how to convert XML to PDF using C# and the powerful IronPDF library.

Why Convert XML to PDF?

Before diving into the implementation, let’s understand the motivation behind converting XML to PDF:

  • Print-Ready Documents: PDF files are printer-friendly and preserve formatting across platforms.
  • Archival and Sharing: PDFs are ideal for archiving and sharing structured XML data in a readable format.
  • Legal and Compliance: PDF is widely accepted for legal, tax, and compliance-related documentation.
  • Presentation Layer: While XML contains raw data, PDF is more suited for displaying that data in a visually appealing manner.

Why Choose IronPDF?

There are several reasons developers choose IronPDF to handle PDF generation tasks:

  • HTML-to-PDF Rendering: IronPDF can convert HTML (generated from XML) into high-quality PDFs.
  • C# Integration: It’s a .NET-native library, which makes it easy to use with C#, ASP.NET, or .NET Core apps.
  • No Complex Dependencies: No need for third-party tools like wkhtmltopdf or external drivers.
  • Feature-Rich: Offers headers, footers, watermarks, password protection, form filling, JavaScript rendering, and more.

IronPDF

Overview of the Process

Converting XML to PDF using IronPDF in C# involves three main steps:

  1. Load the XML file.
  2. Transform the XML into styled HTML using XSLT or manual parsing method.
  3. Convert the HTML into PDF using IronPDF.

Let’s break down each of these steps with code examples.

Step 1: Load XML Data

C# makes it easy to work with XML using classes in the System.Xml namespace. You can load an XML file using XDocument, XmlDocument, or XmlReader.

Here's a sample XML file representing a customer invoice:

<Invoice>
  <InvoiceNumber>INV-2025</InvoiceNumber>
  <Date>2025-07-21</Date>
  <Customer>
    <Name>Simran Kohli</Name>
    <Email>simran@example.com</Email>
  </Customer>
  <Items>
    <Item>
      <Description>IronPDF License</Description>
      <Quantity>1</Quantity>
      <Price>399.00</Price>
    </Item>
    <Item>
      <Description>Extended Support</Description>
      <Quantity>1</Quantity>
      <Price>99.00</Price>
    </Item>
  </Items>
</Invoice>
Enter fullscreen mode Exit fullscreen mode

We can load this XML into C# like so:

XDocument doc = XDocument.Load("invoice.xml");
Enter fullscreen mode Exit fullscreen mode

Or, if it’s a string:

XDocument doc = XDocument.Parse(xmlString);
Enter fullscreen mode Exit fullscreen mode

Step 2: Transform XML to HTML

IronPDF does not render raw XML. Instead, it converts HTML into PDF. So we need to transform our XML into a nicely styled HTML structure.

Option A: Use XSLT

XSLT (Extensible Stylesheet Language Transformations) allows transforming XML into HTML via a separate .xslt stylesheet.

invoice.xslt:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:template match="/">
    <html>
      <head>
        <style>
          body { font-family: Arial; }
          table { border-collapse: collapse; width: 100%; }
          th, td { border: 1px solid #ccc; padding: 8px; }
        </style>
      </head>
      <body>
        <h2>Invoice: <xsl:value-of select="Invoice/InvoiceNumber"/></h2>
        <p>Date: <xsl:value-of select="Invoice/Date"/></p>
        <p>Customer: <xsl:value-of select="Invoice/Customer/Name"/></p>

        <table>
          <tr><th>Description</th><th>Qty</th><th>Price</th></tr>
          <xsl:for-each select="Invoice/Items/Item">
            <tr>
              <td><xsl:value-of select="Description"/></td>
              <td><xsl:value-of select="Quantity"/></td>
              <td><xsl:value-of select="Price"/></td>
            </tr>
          </xsl:for-each>
        </table>
      </body>
    </html>
  </xsl:template>
</xsl:stylesheet>
Enter fullscreen mode Exit fullscreen mode

Then, transform the XML using XslCompiledTransform and a reader:

using System.Xml.Xsl;

var xslt = new XslCompiledTransform();
xslt.Load("invoice.xslt");

using var sw = new StringWriter();
using var xmlReader = XmlReader.Create("invoice.xml");
using var htmlWriter = XmlWriter.Create(sw);

xslt.Transform(xmlReader, htmlWriter);
string htmlContent = sw.ToString();
Enter fullscreen mode Exit fullscreen mode

Option B: Manually Create HTML in Code

If the structure is simple or dynamic, you can generate HTML using C# string builders:

var sb = new StringBuilder();
sb.Append("<html><body><h1>Invoice</h1>");
sb.Append($"<p>Date: {doc.Root.Element("Date")?.Value}</p>");
sb.Append("<table border='1'><tr><th>Description</th><th>Qty</th><th>Price</th></tr>");

foreach (var item in doc.Descendants("Item"))
{
    string desc = item.Element("Description")?.Value;
    string qty = item.Element("Quantity")?.Value;
    string price = item.Element("Price")?.Value;

    sb.Append($"<tr><td>{desc}</td><td>{qty}</td><td>{price}</td></tr>");
}

sb.Append("</table></body></html>");
string htmlContent = sb.ToString();
Enter fullscreen mode Exit fullscreen mode

Step 3: Convert HTML to PDF Using IronPDF

Now that you have the HTML string ready, converting it into a PDF using IronPDF is straightforward.

Install IronPDF

First, install IronPDF via NuGet:

Install-Package IronPdf
Enter fullscreen mode Exit fullscreen mode

Install IronPDF

Or in .csproj:

<PackageReference Include="IronPdf" Version="2025.x.x" />
Enter fullscreen mode Exit fullscreen mode

Convert HTML to PDF

using IronPdf;

var renderer = new HtmlToPdf();
var pdfDoc = renderer.RenderHtmlAsPdf(htmlContent);

// Save the PDF
pdfDoc.SaveAs("invoice.pdf");

Enter fullscreen mode Exit fullscreen mode

PDF Output

You can also specify custom options:

renderer.PrintOptions.MarginTop = 20;
renderer.PrintOptions.PaperSize = PdfPrintOptions.PdfPaperSize.A4;
renderer.PrintOptions.DPI = 300;
renderer.PrintOptions.EnableJavaScript = true;
Enter fullscreen mode Exit fullscreen mode

Advanced Features

Add Header/Footer

renderer.PrintOptions.Header = new SimpleHeaderFooter()
{
    CenterText = "Invoice Header",
    DrawDividerLine = true
};

renderer.PrintOptions.Footer = new SimpleHeaderFooter()
{
    LeftText = "Page {page} of {total-pages}",
    DrawDividerLine = true
};
Enter fullscreen mode Exit fullscreen mode

Merge Multiple XMLs into a Single PDF

If you want to create a batch of invoices from multiple XML files:

var mergedPdf = new PdfDocument();
foreach (var file in Directory.GetFiles("Invoices", "*.xml"))
{
    using var reader = XmlReader.Create(file);
    var doc = XDocument.Load(reader);
    string html = GenerateHtmlFromXml(doc);
    var pdf = renderer.RenderHtmlAsPdf(html);
    mergedPdf.AppendPdf(pdf);
}

mergedPdf.SaveAs("AllInvoices.pdf");
Enter fullscreen mode Exit fullscreen mode

Trial Version Note

IronPDF offers a free trial version, which adds a watermark to generated PDFs. For commercial use or production deployment, you’ll need to purchase a license from the Iron Software website.

The trial is ideal for testing functionality, exploring the API, and validating use cases before committing to the full version.

Wrapping Up

Converting XML to PDF in C# using IronPDF is both powerful and developer-friendly. By combining C#'s native XML handling with IronPDF’s HTML-to-PDF engine, you can generate beautifully formatted documents for reporting, archiving, billing, and much more.

Whether you use XSLT or manually build your HTML templates, IronPDF makes the final PDF generation step seamless. And with added features like headers, footers, page numbers, and styling options, you have full control over the look and feel of your documents.

IronPDF hits the sweet spot for developers who need a reliable, high-level API without diving into low-level PDF object models. IronPDF offers a fully functional free trial with a license key that allows developers to evaluate its features before purchasing a commercial license.

Key Takeaways

  • Load and parse XML using XDocument or XmlDocument.
  • Convert XML to HTML using XSLT or string builders.
  • Render HTML to PDF using IronPDF’s HtmlToPdf class.
  • Add polish with headers, footers, styles, and layout options.
  • Try the trial version and unlock full features with a license.

Start transforming your XML data into professional PDFs today with IronPDF!

Top comments (0)