Generate PDF documents in .NET using PDFsharp

Introduction

In this post, we will see how to create PDF documents in .NET using PDFSharp library.

PDFsharp is the Open Source .NET library that easily creates and processes PDF documents on the fly from any .NET language. The same drawing routines can be used to create PDF documents, draw on the screen, or send output to any printer.

PDFsharp and MigraDoc Foundation are published under the MIT License. You can see the details on this link.

Create Console Project

First, let’s create a .NET project. You can use Visual Studio or dotnet-cli for this purpose. I used following command to create a .NET Core console application.

dotnet new console

Install using nuget

We also need to install nuget packages. Following are the packages you can install. However, if you download the code, then those are already added. You can simple restore the packages.

dotnet add package PdfSharp --version 1.50.5147
dotnet add package System.Drawing.Common
dotnet add package System.Text.Encoding.CodePages //for .NET core

Code

This example code is taken from the PDFsharp website. However, I made some changes to get it working. For example notice that first statement where I am registering the Code-Pages encoding provider.

Output

And now if you open up the file, you will see that text is written in the file.

Summary

This was a very basic introduction of generating PDF using PDFsharp library. We saw that the API of this library is simple and it works well with .NET. There are a lot of other settings and options are available in this library, which you can check on the official webpage of PDFsharp.

The source code is of this example is available on this git-repo.

References