Mastering PDFsharp: A Practical Guide to Creating PDFs with C#
PDFsharp is a .NET library for creating and processing PDF documents programmatically. This guide walks through the essentials: installation, creating documents, adding text and graphics, working with fonts and images, basic layout, saving, and common tips for reliable output. Examples use C# and target .NET 6+ (API is similar for earlier .NET Framework versions).
1. Setup and installation
- Add the PDFsharp nuget package:
bash
dotnet add package PdfSharp - For advanced typography and better font handling use PdfSharpCore or the MigraDoc extension (PdfSharp + MigraDoc) depending on your project target.
2. Creating a simple PDF
- Minimal example to create a one-page PDF with text:
csharp
using PdfSharp.Pdf;using PdfSharp.Drawing; var doc = new PdfDocument();doc.Info.Title = “Sample PDF”;var page = doc.AddPage();XGraphics gfx = XGraphics.FromPdfPage(page);XFont font = new XFont(“Verdana”, 20, XFontStyle.Bold);gfx.DrawString(“Hello PDFsharp!”, font, XBrushes.Black, new XPoint(40, 80));doc.Save(“sample.pdf”); - Notes: XGraphics is used for drawing; XFont names must be available on the host system.
3. Text layout and paragraphs
- For simple text blocks, measure and wrap manually:
csharp
string text = “Long paragraph…”;XRect rect = new XRect(40, 100, page.Width - 80, page.Height - 140);XTextFormatter tf = new XTextFormatter(gfx);tf.Alignment = XParagraphAlignment.Left;tf.DrawString(text, new XFont(“Arial”, 12), XBrushes.Black, rect, XStringFormats.TopLeft); - For complex document layout with headers, footers, and flowable paragraphs, prefer MigraDoc (built on PDFsharp).
4. Drawing shapes, lines, and colors
- Lines, rectangles, and fills:
csharp
gfx.DrawLine(XPens.Black, 40, 200, page.Width - 40, 200);gfx.DrawRectangle(XBrushes.LightGray, 40, 220, 200, 100);gfx.DrawEllipse(XPens.Blue, XBrushes.AliceBlue, 260, 220, 100, 60); - Use XPen to control stroke thickness and dash styles.
Leave a Reply