HTML to PDF in C#: Report PDFs with Xceed PDF Library for .NET

Most report exports start as HTML to PDF conversions and end up maintaining a browser engine on the server. This tutorial builds a sales report PDF directly from a C# model with the Xceed PDF Library for .NET, streams it from ASP.NET Core, and explains when a Chromium-based converter is the better fit.

The Xceed PDF Library for .NET (NuGet: Xceed.PdfLibrary.NET 3.1) generates report PDFs from C# objects instead of rendering HTML. This tutorial builds a sales report with PdfDocument.Create, styles text through TextStyle and ParagraphStyle, adds content with Page.AddParagraph, and saves with SaveOptions. Next, it streams the PDF from an ASP.NET Core endpoint and reloads the file to verify its text. The library has no HTML or CSS engine, so choose a Chromium-based converter such as IronPDF or PuppeteerSharp when you need an exact copy of a web page. Many teams combine both approaches: browser output for designed pages, and Xceed for data reports, merging, signing, and standards validation.

Most reporting features start with the same ticket: export this screen as a PDF. Teams usually reach for HTML to PDF conversion first, because the report already exists as a Razor view or a template. However, that path puts a browser engine on your server. The output can also change whenever the engine, the installed fonts, or the CSS changes.

This tutorial takes a different route. Instead of rendering markup, it maps a C# report model straight to PDF content with the Xceed PDF Library for .NET, using NuGet package Xceed.PdfLibrary.NET version 3.1.26464.8460. You will build a sales report, stream it from ASP.NET Core, and then read it back to verify the text.

The guide also explains when a browser-based converter is still the right tool, and how the two approaches work together. If you searched for "generar PDF C#", the same code applies to Spanish-language or any other localized report, since the content comes from your own data.

Why HTML to PDF Pipelines Break in Production

Many teams treat a report as a web page that happens to print. As a result, they inherit every quirk of print CSS. Page breaks split table rows, running headers drift, and fonts differ between a developer laptop and a Linux container. Headless Chromium also adds memory pressure and a child process that every server has to supervise.

The base class library does not fill this gap either. For example, System.Drawing.Printing targets printers rather than PDF files. In addition, Microsoft documents that System.Drawing.Common is supported only on Windows since .NET 6, which rules it out for cross-platform report services.

Meanwhile, most business reports are data first. A sales summary is a title, a period, a set of rows, and a total. Therefore, generating the PDF from the data model removes a whole rendering layer, along with the HTML template that sits between your code and the final document.

How the Xceed PDF Library for .NET Builds Report PDFs

The Xceed PDF Library for .NET exposes a document object model in the Xceed.PdfLibrary.NET namespace. PdfDocument.Create opens a new file or stream, Page.AddParagraph lays out styled text, and PdfDocument.Save writes the result. The same object model also covers the work that usually follows generation:

  • Text styling through TextStyle: font, size, brush, pen, character spacing, word spacing, and rotation.
  • Paragraph layout through ParagraphStyle: horizontal alignment, line spacing type, custom line spacing, and indentation.
  • Search and edit through FindText, ReplaceText, RemoveText, and UpdateTextStyle on each page.
  • Assembly through Merge, Split, bookmarks, attachments, and watermarks.
  • Trust and compliance through Sign with PFX or certificate-store credentials, ValidateSignatures, and ValidatePdfStandard, which is new in version 3.1.
  • Interactive forms with text box, check box, combo box, list box, radio button, and signature fields.

Where Browser-Based HTML to PDF Converters Fit

The Xceed PDF Library does not include an HTML or CSS rendering engine. So when your PDF has to look exactly like an existing web page, and that matters more than predictable layout, a browser-based converter is the better fit. Alternatives in this space include IronPDF and PuppeteerSharp, which render with Chromium. Other commercial PDF libraries also offer HTML conversion features. These tools reproduce modern CSS closely, but you pay for it with a larger runtime footprint.

A common hybrid uses both. A browser engine renders the designed cover pages, while Xceed generates the data-driven pages and then merges, watermarks, or signs the final file. That split keeps the browser dependency off the hot path for routine reports.

Tutorial: Generate a PDF Report in C#

The steps below target .NET 8 and work in a console app, a worker service, or ASP.NET Core.

Step 1: Install the NuGet Package

Add the Xceed.PdfLibrary.NET package on NuGet to your project file:

NuGet Package Reference

<ItemGroup>
  <PackageReference Include="Xceed.PdfLibrary.NET" Version="3.1.26464.8460" />
</ItemGroup>

Import Xceed.PdfLibrary.NET, not Xceed.Pdf. The second namespace is a lower-level internal layer, and PdfDocument does not live there.

Step 2: Define the Report Model and Layout

Keep the report model free of PDF types so you can unit test it on its own. The ReportLayout record holds the paragraph styles for headings and body text.

Report Model and Layout

using System.Collections.Generic;
using Xceed.PdfLibrary.NET;
 
public sealed record ReportLine(string Product, int Quantity, decimal Total);
 
public sealed record SalesReport(string Title, string Period, IReadOnlyList<ReportLine> Lines);
 
public sealed record ReportLayout(ParagraphStyle Heading, ParagraphStyle Body)
{
    // default(...) selects each enum's zero-value member. Replace it with explicit
    // ParagraphHorizontalAlignment and LineSpacingType members from the API reference.
    public static ReportLayout CreateDefault() => new ReportLayout(
        new ParagraphStyle(default(ParagraphHorizontalAlignment), default(LineSpacingType)),
        new ParagraphStyle(default(ParagraphHorizontalAlignment), default(LineSpacingType)));
}

Each ParagraphStyle takes an alignment and a line spacing type in its constructor. In addition, its CustomLineSpacingValue property accepts an exact spacing value when your design calls for one.

Step 3: Create Reusable Text Styles

TextStyle uses a fluent API, so every Set method returns a TextStyle. Start from TextStyle.GetDefault(document) so each style uses that document's default font.

Reusable PDF Text Styles

using Xceed.PdfLibrary.NET;
 
public static class ReportStyles
{
    public static TextStyle Title(PdfDocument document) =>
        TextStyle.GetDefault(document).SetFontSize(20).SetBrush(Brushes.Navy);
 
    public static TextStyle Heading(PdfDocument document) =>
        TextStyle.GetDefault(document)
            .SetFontSize(13)
            .SetCharacterSpacing(0.5)
            .SetBrush(Brushes.DarkSlateGray);
 
    public static TextStyle Body(PdfDocument document) =>
        TextStyle.GetDefault(document).SetFontSize(10).SetBrush(Brushes.Black);
 
    public static TextStyle Muted(PdfDocument document) =>
        TextStyle.GetDefault(document).SetFontSize(8).SetBrush(Brushes.Gray);
}

Step 4: Render the Report onto a Page

The renderer walks the model and calls AddParagraph for each block. Because it receives a PdfDocument rather than a file path, the same code serves files and streams.

Sales Report Renderer

using System.Globalization;
using System.Linq;
using Xceed.PdfLibrary.NET;
 
public static class SalesReportRenderer
{
    private static readonly CultureInfo Currency = CultureInfo.GetCultureInfo("en-US");
 
    public static void Render(PdfDocument document, SalesReport report, ReportLayout layout)
    {
        // First page of the new document.
        Page page = document.Pages.First();
 
        page.AddParagraph(report.Title, ReportStyles.Title(document), layout.Heading);
        page.AddParagraph($"Reporting period: {report.Period}", ReportStyles.Muted(document), layout.Body);
        page.AddParagraph("Line items", ReportStyles.Heading(document), layout.Heading);
 
        foreach (ReportLine line in report.Lines)
        {
            string row = $"{line.Product}  |  Qty {line.Quantity}  |  {line.Total.ToString("C", Currency)}";
            page.AddParagraph(row, ReportStyles.Body(document), layout.Body);
        }
 
        decimal grandTotal = report.Lines.Sum(l => l.Total);
        page.AddParagraph($"Grand total: {grandTotal.ToString("C", Currency)}", ReportStyles.Heading(document), layout.Body);
    }
}

AddParagraph also has an overload that takes a vertical position, which helps when you need to pin a block such as a signature area. Both overloads return a LayoutResult describing the layout pass.

Step 5: Save the PDF to Disk

Set the license key once at startup, then create, render, and save. The SaveOptions.Language property, added in 3.1, records the document language.

Generate and Save the PDF

using Xceed.PdfLibrary.NET;
 
Licenser.LicenseKey = "YOUR-LICENSE-KEY";
 
var report = new SalesReport(
    "Q3 Sales Report",
    "July 1 to September 30, 2026",
    new[]
    {
        new ReportLine("Industrial sensors", 120, 18600m),
        new ReportLine("Gateway units", 35, 12250m),
        new ReportLine("Support contracts", 14, 9800m)
    });
 
PdfDocument document = PdfDocument.Create("SalesReport.pdf");
SalesReportRenderer.Render(document, report, ReportLayout.CreateDefault());
document.Save(new SaveOptions { Language = "en-US" });

The rendered Q3 sales report, generated from a C# model.

Step 6: Stream the PDF from ASP.NET Core

Web apps rarely need a file on disk. Instead, pass a MemoryStream to PdfDocument.Create and return the bytes from a minimal API endpoint.

ASP.NET Core PDF Endpoint

using Xceed.PdfLibrary.NET;
 
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
 
Licenser.LicenseKey = builder.Configuration["Xceed:PdfLicenseKey"];
 
app.MapGet("/reports/sales", () =>
{
    var report = new SalesReport("Q3 Sales Report", "Q3 2026",
        new[] { new ReportLine("Gateway units", 35, 12250m) });
 
    using var buffer = new MemoryStream();
    PdfDocument document = PdfDocument.Create(buffer);
    SalesReportRenderer.Render(document, report, ReportLayout.CreateDefault());
    document.Save(new SaveOptions { Language = "en-US" });
 
    // ToArray works even if the stream was closed during Save.
    return Results.File(buffer.ToArray(), "application/pdf", "sales-report.pdf");
});
 
app.Run();

The ToArray call is a deliberate choice. According to the MemoryStream.ToArray documentation, the method works even after the stream closes, so the endpoint behaves the same whether or not Save disposes the stream.

Verify, Merge, and Sign the Output

Generated reports deserve automated tests. PdfDocument.Load takes a path or stream plus a LoadOptions instance, since no single-argument overload exists. After loading, Page.OrderedText returns the page text in reading order.

Verify Generated PDF Content

PdfDocument generated = PdfDocument.Load("SalesReport.pdf", new LoadOptions());
 
foreach (Page page in generated.Pages)
{
    Console.WriteLine(page.OrderedText);
}
 
Console.WriteLine($"PDF version: {generated.Version}, encrypted: {generated.IsEncrypted}");

In a test project, assert that the text contains "Grand total" and the expected currency value. That check catches template regressions without comparing images.

Beyond verification, the same PdfDocument instance handles finishing work. Merge combines the report with a cover page from any source, including a browser-based converter. Similarly, Sign applies a digital signature to a SignatureFormField using a PfxSigningCredential or StoreSigningCredential. Finally, ValidatePdfStandard checks the output against a PdfStandardProfile before you archive it.

Practical Tips for a PDF Library in .NET

The following notes come from common integration issues with any PDF library for .NET, adapted to the Xceed API:

  • Load license keys from configuration. Licensing works offline: you set Licenser.LicenseKey in code, and nothing calls home. As a result, the same build runs in air-gapped environments.
  • Build styles per document. TextStyle.GetDefault takes a document argument, so derive styles from each document rather than caching one instance across documents.
  • Plan for long reports. Check the LayoutResult that AddParagraph returns, and see the PageCollection reference for adding pages when content overflows.
  • Describe charts for accessibility. Version 3.1 added Image.AlternateDescription, which pairs well with SaveOptions.Language.
  • Upgrading from 3.0? Version 3.1 removed SolidColorBrush, Pen.StrokeBrush, and Pen.SetBrush. Instead, Brushes members now return Brush, and pens take color through Pen.SetPaint. In addition, Brush.FromColor builds a brush from a color value.

For deployment, Xceed uses a per-developer subscription to build and ship, with royalty-free distribution. In practice, you pay no per-server or per-end-user fees when your report service scales out. The license agreement covers the details, and the Xceed blog has more .NET component tutorials.

Generate Report PDFs from C#

Try the Xceed PDF Library for .NET free for 45 days, no credit card required.

Frequently Asked Questions

Can the Xceed PDF Library convert HTML to PDF directly?

No. The library builds PDFs through an object model and does not include an HTML or CSS rendering engine. For HTML to PDF output that must match a web page, use a Chromium-based converter such as IronPDF or PuppeteerSharp. You can then merge, watermark, or sign that output with Xceed.

How do I generate a PDF in C# without a browser engine?

Create a document with PdfDocument.Create, add styled text through Page.AddParagraph using TextStyle and ParagraphStyle, and write it with PdfDocument.Save. The same steps apply to "generar PDF C#" scenarios, since all of the content comes from your C# data model.

Which NuGet package and namespace does the Xceed PDF Library use?

Install Xceed.PdfLibrary.NET, currently version 3.1.26464.8460, and import the Xceed.PdfLibrary.NET namespace. The Xceed.Pdf namespace is a lower-level internal layer and does not contain PdfDocument.

Can I return a generated PDF from an ASP.NET Core endpoint?

Yes. Pass a MemoryStream to PdfDocument.Create, save the document, and return buffer.ToArray() through Results.File with the application/pdf content type.

Does the Xceed PDF Library require online license activation?

No. You set Licenser.LicenseKey in code, and the component never phones home. Applications build and run on fully offline machines.

What changed for brushes and pens in version 3.1?

Version 3.1 removed SolidColorBrush, Pen.StrokeBrush, and Pen.SetBrush. Brushes members now return Brush, pens use Pen.SetPaint, and Brush.FromColor or Brush.FromPaint creates brushes from color or paint values.

Check out Xceed’s Words and PDF Library bundle