Skip to footer content
PRODUCT COMPARISONS
How to Generate PDF in C# (.NET 5) using PDFsharp

How to Generate PDF in C# (.NET 5) using PDFSharp

The video is an instructional guide on how to use the PDFsharp library to generate a PDF file using C# code. The speaker begins by introducing PDFsharp as a tricky but effective library for generating PDF files. The library has advanced features, and unlike many of its competitors, it is completely free. The speaker emphasizes that despite its complexity, PDFsharp is an excellent choice for generating PDF files using C#.

To begin the tutorial, the speaker presents an example of a generated PDF file that consists of three lines of text. The first line of text is not exactly the first one, while the third line of text appears at the bottom right-hand corner. The speaker notes that the order of the text will make sense once they walk through the code. They also explain that they will be using .NET 5 to demonstrate how PDFsharp works. For a broader look at creating PDFs from scratch in C#, IronPDF offers a streamlined alternative approach.

Here is a quick look at how PDFsharp and IronPDF differ across the capabilities most relevant to .NET PDF projects:

Feature IronPDF PDFSharp
HTML to PDF Conversion Yes No
Digital Signatures Yes No
Encryption Yes No
HTML, CSS, and JavaScript Yes No
Professional Support Yes No
Licensing Commercial MIT (Open Source)

Detailed explanations and code examples for each of these differences follow in the sections below. Teams comparing both libraries can test IronPDF's capabilities with a free 30-day trial.

Install and Setup

Before getting into the code, the speaker highlights that setting up the environment for PDFsharp can be quite challenging. They explain that three NuGet packages must be installed before working with PDFsharp NuGet Package Details. The first package is PDFsharp itself, which may generate a warning that it may not match with .NET due to its older version. The other two packages are System.Drawing.Common and System.Text.Encoding.CodePages.

How to Generate PDF in C# (.NET 5) using PDFSharp: Figure 1

The speaker emphasizes that all three packages must be installed before working with PDFsharp; otherwise, the code will throw an error. They explain that the System.Text.Encoding.CodePages package is especially important as it provides the encoding support necessary for generating PDF files. The speaker also notes that failure to install the packages correctly could be difficult to troubleshoot. Teams looking to avoid this multi-package setup entirely can follow the PDFsharp to IronPDF migration guide for a step-by-step transition.

To make PDFSharp work properly, the speaker explains that a provider must be registered for System.Text.Encoding. The provider comes from the System.Text.Encoding.CodePages package, and the speaker highlights the importance of registering the package to ensure that PDFsharp functions correctly. They explain that failing to register the provider will result in an error, which can be challenging to troubleshoot.

Creating a PDF File

Next, the speaker presents a simple console application that uses PDFsharp to generate a PDF file. They explain that before using the library, the using statements for PDFsharp Drawing and PDFsharp PDF must be declared. The speaker then presents the code to generate the PDF file, which involves creating a new document, adding a new page, and drawing the text on the page.

using PdfSharp.Drawing;
using PdfSharp.Pdf;

namespace PdfSharpExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a new PDF document
            PdfDocument document = new PdfDocument();
            // Add a new page
            PdfPage page = document.AddPage();
            // Prepare to draw on the page
            XGraphics gfx = XGraphics.FromPdfPage(page);
            // Define a font
            XFont font = new XFont("Verdana", 20, XFontStyle.Bold);

            // Draw a string to the page
            gfx.DrawString("Hello, PDFsharp!", font, XBrushes.Black,
                new XRect(0, 0, page.Width, page.Height),
                XStringFormats.Center);

            // Save the document
            const string filename = "HelloWorld.pdf";
            document.Save(filename);  
        }
    }
}
using PdfSharp.Drawing;
using PdfSharp.Pdf;

namespace PdfSharpExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a new PDF document
            PdfDocument document = new PdfDocument();
            // Add a new page
            PdfPage page = document.AddPage();
            // Prepare to draw on the page
            XGraphics gfx = XGraphics.FromPdfPage(page);
            // Define a font
            XFont font = new XFont("Verdana", 20, XFontStyle.Bold);

            // Draw a string to the page
            gfx.DrawString("Hello, PDFsharp!", font, XBrushes.Black,
                new XRect(0, 0, page.Width, page.Height),
                XStringFormats.Center);

            // Save the document
            const string filename = "HelloWorld.pdf";
            document.Save(filename);  
        }
    }
}
$vbLabelText   $csharpLabel

The speaker notes that the code for generating the PDF file can be adjusted to include more complex features, such as adding images (see how to convert images to PDF with IronPDF), tables, and charts. They also explain that PDFsharp provides various features for working with fonts, including embedding fonts in the PDF file.

How to Generate PDF in C# (.NET 5) using PDFSharp: Figure 2

The speaker explains the importance of setting up the environment correctly by installing the necessary NuGet packages and registering a provider for System.Text.Encoding. They also present a simple console application that uses PDFsharp to generate a PDF file and demonstrate how the code can be adjusted to include more complex features. The video is an excellent resource for anyone interested in generating PDF files using C# and PDFsharp.

Creating Lists and More Complex Items

In the second part of the video, the speaker begins by introducing a more complex example of creating a PDF document. He emphasizes that it is pointless to have an empty PDF document and proceeds to explain how to create a new page using the PDFSharp library. He notes that the process is similar to creating things in Excel or PowerPoint add-ins, and that once the page is created, it works with a reference that does not require the invocation of another method.

How to Generate PDF in C# (.NET 5) using PDFSharp: Figure 3

The speaker then introduces the XGraphics variable, which provides methods to draw things like text, lines, and images — functionality that IronPDF handles through its text and image stamping API without requiring manual coordinate calculations. The XFont variable is also introduced as a means of setting up a font for use in the PDF document. The speaker notes that the font can be generated somewhere else, but that it is useful to set it up globally if there is a more complex arrangement.

Next, the speaker discusses the DrawString method, which writes text into the PDF file. He notes that the complex part of the method is determining where the text will be drawn and explains the various parameters involved, such as the font, color, and boundaries of where the text might align. He also explains the use of the XBrushes variable to set the color of the text.

Explaining DrawString and Other Methods

The speaker then presents several examples of using the DrawString method with different parameters, such as aligning the text in the center, aligning it at the bottom left, and specifying the exact coordinates where the text will be placed. He notes that the last option is the most customizable and offers a great deal of flexibility.

How to Generate PDF in C# (.NET 5) using PDFSharp: Figure 4

The speaker explains how to create a table using graphics in the C# programming language. They cover how to insert images, strings, and lines, as well as how to draw arcs and barcodes using the graphics feature — tasks that IronPDF simplifies through its rendering options for margins, headers, and DPI. They also explain the importance of trial and error when working with coordinates and how to draw lines to separate rows.

The speaker also discusses the table header and the need for a starting point for values and the line. They explain how to adjust the y position and add rows of records, and how to move to another page when the table exceeds a certain number of records. Finally, they mention the importance of resetting values for each page.

Which Library Should You Choose?

In conclusion, the speaker emphasizes the importance of being familiar with Microsoft Office add-ins when working with PDFSharp and offers his own course on the topic. He also notes that the library is highly versatile and can be used to create a wide range of PDF documents, from simple text documents to more complex ones with images, graphics, and custom layouts.

What Is IronPDF?

IronPDF is a C# PDF library for creating, editing, and manipulating PDF documents. It ships as a single NuGet package — Install-Package IronPdf — and integrates with .NET applications without requiring additional dependency setup.

PDFsharp provides solid low-level drawing control and ships under a permissive MIT license — two genuine strengths that have made it a staple in many .NET projects. Where teams often hit friction is when requirements grow beyond coordinate-based rendering into areas like HTML-to-PDF conversion, digital signatures, or document encryption. IronPDF is a commercially supported library that addresses those scenarios as first-class operations, with professional support and an API surface designed around common document-generation workflows including HTML, CSS, and JavaScript rendering.

Features

Features IronPDF PDFSharp
Convert HTML to PDF Yes No
Professional support Yes No
HTML, CSS, and JavaScript Support Yes No
Digital signatures Yes No
Encryption Yes No

One of the key features of IronPDF is its ability to convert HTML to PDF using IronPDF, making it straightforward to create PDF documents from web pages. HTML-to-PDF conversion is outside PDFsharp's current scope — it operates at the coordinate-drawing level — so teams needing that capability typically add a separate rendering library or evaluate IronPDF's built-in Chromium engine.

IronPDF also includes support for digital signatures and PDF encryption with password protection, which is crucial for sensitive documents that require secure handling. PDFsharp is not designed to address these security scenarios, so teams with compliance or document-protection requirements often find this a natural inflection point for evaluating IronPDF.

IronPDF provides a broader feature set and a more comprehensive support offering compared to PDFsharp, covering HTML rendering, encryption, and digital signatures in a single NuGet package. It is a commercial product, however, so teams whose requirements fit within PDFsharp's coordinate-drawing model — and who do not need HTML conversion or built-in security features — may prefer PDFsharp's MIT-licensed, open-source approach.

Beyond license cost, total project cost includes the developer hours spent assembling separate rendering libraries, managing coordinate-based page layouts for complex documents, and troubleshooting the multi-package setup that PDFsharp requires. For teams evaluating cost over a multi-year project lifecycle, these integration and maintenance costs frequently eclipse the difference between open-source and commercial licensing.

Ready to see how IronPDF fits into your workflow? Download a free 30-day trial to test every feature covered in this comparison.

Please notePDFsharp is a registered trademark of its respective owner. This site is not affiliated with, endorsed by, or sponsored by PDFsharp. All product names, logos, and brands are property of their respective owners. Comparisons are for informational purposes only and reflect publicly available information at the time of writing.

Frequently Asked Questions

How can I generate a PDF file using PDFsharp in C#?

To generate a PDF using PDFsharp, you need to create a new PDF document, add a page to it, and utilize the XGraphics object to draw text or graphics. Make sure to include using statements for PdfSharp.Drawing and PdfSharp.Pdf namespaces.

What are the essential NuGet packages required for PDFsharp?

To work efficiently with PDFsharp, you need to install the following NuGet packages: PDFsharp, System.Drawing.Common, and System.Text.Encoding.CodePages. These packages are crucial for encoding support and proper PDF generation.

How does IronPDF compare with PDFsharp for PDF generation in C#?

IronPDF is a commercial library that offers advanced features like HTML to PDF conversion, digital signatures, and encryption, which are not available in PDFsharp. It also provides better documentation and professional support, making it more user-friendly for complex tasks.

What are the limitations of using PDFsharp for PDF generation?

PDFsharp does not support HTML, CSS, or JavaScript, which limits its use cases. It requires a good understanding of encoding setup and Microsoft Office add-ins for complex documents, which can make it less intuitive compared to IronPDF.

Why is the System.Text.Encoding.CodePages package important for PDFsharp?

The System.Text.Encoding.CodePages package provides necessary encoding support when generating PDF files with PDFsharp. Without correctly installing and registering this package, you may encounter encoding-related errors.

Can I convert HTML to PDF using a free C# library?

No, PDFsharp does not support HTML to PDF conversion. For such functionality, you would need a commercial library like IronPDF, which offers this feature along with other advanced capabilities.

How can I troubleshoot common errors in PDFsharp?

Common errors in PDFsharp often arise from incorrect setup of NuGet packages or encoding issues. Ensure that all required packages, including System.Text.Encoding.CodePages, are installed and registered properly to resolve such issues.

What advanced features are available in IronPDF for C# developers?

IronPDF offers advanced features such as HTML to PDF conversion, digital signatures, encryption, and the ability to handle CSS and JavaScript. It also provides integration with .NET applications and professional support, making it a powerful tool for developers.

How can I customize text layout in a PDF using PDFsharp?

Using PDFsharp, you can customize text layout in a PDF by utilizing the DrawString method of the XGraphics class. This allows you to set properties like font, color, and text alignment within specified boundaries.

Is PDFsharp suitable for creating complex PDF documents in C#?

PDFsharp can create complex PDF documents, but it requires a solid understanding of encoding and Microsoft Office add-ins. IronPDF may be a better option for complex tasks due to its more intuitive API and additional features.

Curtis Chau
Technical Writer

Curtis Chau holds a Bachelor’s degree in Computer Science (Carleton University) and specializes in front-end development with expertise in Node.js, TypeScript, JavaScript, and React. Passionate about crafting intuitive and aesthetically pleasing user interfaces, Curtis enjoys working with modern frameworks and creating well-structured, visually appealing manuals.

...

Read More

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me