Codementor Events

How to Implement PDFsharp Library in .NET 8 (Step-by-Step Guide)

Published Mar 21, 2025

Introduction

Generating PDF files is a common requirement for many applications, whether for reports, invoices, or receipts. PDFsharp is a lightweight, open-source library that makes it easy to create and manipulate PDFs in C# applications.

In this guide, we'll walk through how to set up and use PDFsharp in a .NET 8 web application. This tutorial is designed for beginners, so we'll keep the explanations simple and clear.

What is PDFsharp?

PDFsharp is a .NET library that allows you to create, modify, and read PDF documents. It is free and does not require any external dependencies. Unlike other libraries (like iTextSharp), PDFsharp has a simpler API and does not require additional licensing for commercial use.

Why Use PDFsharp?

✔ Free and Open-Source
✔ Supports text, images, tables, and graphics
✔ Works with .NET 8 and later
✔ No external dependencies
✔ Lightweight and fast

Setting Up PDFsharp in a .NET 8 Project

Step 1: Create a .NET 8 Web API or MVC Project

Open a terminal or Visual Studio and create a new .NET 8 Web API project:

mkdir PdfSharpDemo
cd PdfSharpDemo
dotnet new webapi

Step 2: Install PDFsharp
Run the following command to install PDFsharp via NuGet:

dotnet add package PdfSharp-MigraDoc

OR, if using Visual Studio:

Open NuGet Package Manager

Search for PdfSharp-MigraDoc

Click Install

Generating a Simple PDF

Now, let's create a PDF generator class that will generate a simple PDF file with text, a table, and a footer.

Step 3: Create a PDF Generator Class
Create a new file PdfGenerator.cs inside your project:

using System;
using System.IO;
using PdfSharp.Pdf;
using PdfSharp.Drawing;

public class PdfGenerator
{
    public static byte[] GenerateSamplePdf()
    {
        using (MemoryStream ms = new MemoryStream())
        {
            PdfDocument pdf = new PdfDocument();
            pdf.Info.Title = "Sample PDF Report";

            PdfPage page = pdf.AddPage();
            XGraphics gfx = XGraphics.FromPdfPage(page);
            XFont titleFont = new XFont("Arial", 16, XFontStyle.Bold);
            XFont textFont = new XFont("Arial", 10, XFontStyle.Regular);

            int margin = 40;
            int y = margin;

            // Title
            gfx.DrawString("Sales Report", titleFont, XBrushes.Black, new XPoint(margin, y));
            y += 30;

            // Content
            gfx.DrawString("This is a sample PDF generated using PDFsharp.", textFont, XBrushes.Black, new XPoint(margin, y));
            y += 20;

            // Footer
            gfx.DrawLine(XPens.Black, margin, page.Height - 60, page.Width - margin, page.Height - 60);
            gfx.DrawString("Generated by PDFsharp | www.company.com", textFont, XBrushes.Black, new XPoint(margin, page.Height - 40));

            pdf.Save(ms);
            return ms.ToArray();
        }
    }
}

Step 4: Create an API Endpoint to Download the PDF

Now, let's create a Web API controller to serve the generated PDF.
Create a new controller ExportController.cs:

using Microsoft.AspNetCore.Mvc;

[Route("api/[controller]")]
[ApiController]
public class ExportController : ControllerBase
{
    [HttpGet("download-sample-pdf")]
    public IActionResult DownloadSamplePdf()
    {
        byte[] pdfBytes = PdfGenerator.GenerateSamplePdf();
        return File(pdfBytes, "application/pdf", "SampleReport.pdf");
    }
}

Running the Application

Now, run your .NET 8 Web API project:

dotnet run

Open your browser and go to:

🔗 https://localhost:5001/api/export/download-sample-pdf

You should see a PDF file downloading!

Enhancing the Report (Adding Tables & Styling)

If you want to generate a professional report with tables and formatting, modify PdfGenerator.cs like this:

// Draw Table Headers with Background color
gfx.DrawRectangle(XBrushes.Gray, new XRect(margin, y, page.Width - (2 * margin), 20));
gfx.DrawString("Product Name", textFont, XBrushes.White, new XPoint(margin + 5, y + 15));
gfx.DrawString("Quantity", textFont, XBrushes.White, new XPoint(margin + 200, y + 15));
gfx.DrawString("Price", textFont, XBrushes.White, new XPoint(margin + 300, y + 15));
y += 30;

// Sample Data
string[,] data = {
    { "Product A", "2", "$15" },
    { "Product B", "1", "$25" },
    { "Product C", "3", "$10" }
};

// Draw Table Rows for the above data
double subtotal = 0;
for (int i = 0; i < data.GetLength(0); i++)
{
    gfx.DrawString(data[i, 0], textFont, XBrushes.Black, new XPoint(margin, y));
    gfx.DrawString(data[i, 1], textFont, XBrushes.Black, new XPoint(margin + 200, y));
    gfx.DrawString(data[i, 2], textFont, XBrushes.Black, new XPoint(margin + 300, y));
    subtotal += Convert.ToDouble(data[i, 2].Trim('$'));
    y += 20;
}

// Calculate the Subtotal
gfx.DrawString("Subtotal:", textFont, XBrushes.Black, new XPoint(margin + 200, y));
gfx.DrawString("$" + subtotal, textFont, XBrushes.Black, new XPoint(margin + 300, y));

Conclusion

In this guide, we covered:

What is PDFsharp and why use it?
How to install PDFsharp in a .NET 8 project
How to generate a simple PDF with text
How to create a Web API endpoint for downloading PDFs
How to enhance reports with tables and background colors

This tutorial gives you everything you need to start working with PDFsharp in .NET 8!

Have questions? Drop a comment below!


Happy coding!

Follow Me for more interested Article

Visit my blogs website

Support me on Patreon

I would love to see you in my followers list.

Discover and read more posts from Riza
get started