Skip to footer content
PRODUCT COMPARISONS

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.

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);  
        }
    }
}
Imports PdfSharp.Drawing

Imports PdfSharp.Pdf



Namespace PdfSharpExample

	Friend Class Program

		Shared Sub Main(ByVal args() As String)

			' Create a new PDF document

			Dim document As New PdfDocument()

			' Add a new page

			Dim page As PdfPage = document.AddPage()

			' Prepare to draw on the page

			Dim gfx As XGraphics = XGraphics.FromPdfPage(page)

			' Define a font

			Dim font As 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 filename As String = "HelloWorld.pdf"

			document.Save(filename)

		End Sub

	End Class

End Namespace
$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, 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. 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. 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.

Conclusion

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.

IronPDF: A C# PDF Library

IronPDF is a C# PDF library for creating, editing, and manipulating PDF documents. It is designed to be easy to use and integrates with .NET applications seamlessly.

Compared to PDF Sharp, IronPDF offers several advantages. Firstly, it is a commercial product and comes with professional support, which is not available with PDF Sharp. Secondly, IronPDF has better documentation and a more intuitive API, making it easier for developers to get started and work with the library. Additionally, IronPDF has a richer set of features, including advanced PDF creation options and support for working with HTML, CSS, and JavaScript.

Features

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

One of the key features of IronPDF is its ability to convert HTML to PDF using IronPDF, making it easy to create PDF documents from web pages. This feature is not available in PDF Sharp, which limits its use cases.

IronPDF also has support for digital signatures and encryption, which is crucial for sensitive documents that require secure handling. This feature is not available in PDF Sharp.

IronPDF is a more powerful and user-friendly PDF library compared to PDF Sharp, with additional features and better support options. However, it is also a commercial product, so it may not be the best choice for developers looking for a free or open-source solution.

Frequently Asked Questions

What is a library used for generating PDF files using C# code?

PDFsharp is a free library used for generating PDF files using C# code. It offers advanced features but is known for its complexity. The library requires setting up the environment properly with necessary NuGet packages.

What packages are required to work with a specific PDF library?

To work with PDFsharp, you need to install three NuGet packages: PDFsharp itself, System.Drawing.Common, and System.Text.Encoding.CodePages. These packages ensure proper functionality and prevent errors.

How do you generate a simple PDF file using a C# library?

You can generate a simple PDF by creating a new PDF document, adding a page, and using XGraphics to draw text. The code involves setting up using statements for PDFsharp Drawing and PDFsharp PDF libraries.

What is a commercial C# PDF library that offers additional features?

IronPDF is a commercial C# PDF library that offers features like HTML to PDF conversion, professional support, and a more intuitive API. It is more powerful than PDFsharp but comes at a cost.

What are the advantages of using a commercial PDF library for C#?

IronPDF offers several advantages, including HTML to PDF conversion, digital signatures, encryption, and professional support. It is designed to integrate seamlessly with .NET applications.

Can a free PDF library handle HTML, CSS, and JavaScript?

No, PDFsharp does not support HTML, CSS, and JavaScript. This limits its use cases compared to IronPDF, which does support these technologies.

What is the importance of a specific encoding package in a PDF library?

The System.Text.Encoding.CodePages package is important for providing the necessary encoding support for generating PDF files in PDFsharp. Failing to install and register it correctly can lead to errors.

How can you customize text placement in a PDF using a library's method?

You can customize text placement in a PDF using the DrawString method in PDFsharp. This involves setting parameters like font, color, and text alignment within defined boundaries.

What additional features does a commercial PDF library have compared to a free one?

IronPDF offers additional features such as HTML to PDF conversion, digital signatures, encryption, and more advanced PDF creation options, which are not available in PDFsharp.

Is a free PDF library suitable for creating complex PDF documents?

While PDFsharp can create complex PDF documents, it requires a good understanding of Microsoft Office add-ins and the correct setup of the environment. It may not be as intuitive as IronPDF for complex tasks.

Chipego
Software Engineer
Chipego has a natural skill for listening that helps him to comprehend customer issues, and offer intelligent solutions. He joined the Iron Software team in 2023, after studying a Bachelor of Science in Information Technology. IronPDF and IronOCR are the two products Chipego has been focusing on, but his knowledge of all products is growing daily, as he finds new ways to support customers. He enjoys how collaborative life is at Iron Software, with team members from across the company bringing their varied experience to contribute to effective, innovative solutions. When Chipego is away from his desk, he can often be found enjoying a good book or playing football.