Generating PDF Reports in C# (.NET): Library Overview and Examples
In modern .NET platform development, creating PDF documents is a common task. Whether it's generating invoices, reports, waybills, or analytical dashboards, C# provides powerful tools for working with PDFs. In this article, we will cover three popular libraries: iTextSharp, QuestPDF, and PdfSharp. You will learn which one to choose for a specific task and see working code examples.
1. iTextSharp (iText 7 for .NET)
iTextSharp is a port of the popular Java library iText for .NET. It is the most mature and feature-rich solution, supporting complex layouts, tables, images, annotations, and digital signatures. However, commercial use requires purchasing a license (AGPL for open-source).
Installation
dotnet add package itext7Example: Simple Report with a Table
using iText.Kernel.Pdf;using iText.Layout;using iText.Layout.Element;
public void CreatePdfReport(){ string filePath = "report.pdf"; using (PdfWriter writer = new PdfWriter(filePath)) using (PdfDocument pdf = new PdfDocument(writer)) using (Document document = new Document(pdf)) { document.Add(new Paragraph("Sales Report for March") .SetBold().SetFontSize(18));
Table table = new Table(3); table.AddCell("Product"); table.AddCell("Quantity"); table.AddCell("Price"); table.AddCell("Laptop"); table.AddCell("12"); table.AddCell("75,000 ₽"); table.AddCell("Monitor"); table.AddCell("5"); table.AddCell("32,000 ₽");
document.Add(table); }}Pros: maximum flexibility, support for complex structures, digital signatures.
Cons: complex API for beginners, licensing for commercial use.
2. QuestPDF
QuestPDF is a modern library with a fluent interface and a built-in rendering engine. It allows you to describe a document in a declarative style, similar to HTML/CSS. It is ideal for generating standard reports with repeating elements.
Installation
dotnet add package QuestPDFExample: Invoice with Header and Table
using QuestPDF.Fluent;using QuestPDF.Helpers;using QuestPDF.Infrastructure;
public byte[] GenerateInvoice(){ return Document.Create(container => { container.Page(page => { page.Size(PageSizes.A4); page.Margin(20); page.Header().Text("Invoice No. 12345") .SemiBold().FontSize(20).FontColor(Colors.Blue.Darken2);
page.Content().Table(table => { table.ColumnsDefinition(columns => { columns.RelativeColumn(); columns.RelativeColumn(); columns.RelativeColumn(); });
table.Header(header => { header.Cell().Background(Colors.Grey.Lighten3).Text("Service"); header.Cell().Background(Colors.Grey.Lighten3).Text("Cost"); header.Cell().Background(Colors.Grey.Lighten3).Text("Quantity"); });
table.Cell().Text("Consultation"); table.Cell().Text("5,000 ₽"); table.Cell().Text("2");
table.Cell().Text("Development"); table.Cell().Text("15,000 ₽"); table.Cell().Text("1"); });
page.Footer().AlignCenter().Text("Thank you for your cooperation!"); }); }).GeneratePdf();}Pros: simple and readable code, excellent performance, free for commercial