PDFSharp HTML to PDF Example and Tutorials Comparison

PDFSharp and IronPDF give engineers the tools to generate, manipulate, edit, format, and print PDF documents from various inputs. Working in .NET and .NET Core, we must choose tools that best suit our projects and requirements. Using code samples and walk-through tutorials, we take a look at how to accomplish different tasks using these products below.

PDF from HTML String
private void HTMLString()
{
	// Render any HTML fragment or document to HTML
	var Renderer = new IronPdf.HtmlToPdf();
	var PDF = Renderer.RenderHtmlAsPdf("<h1>Hello IronPDF</h1>");

	Renderer.PrintOptions.Footer = new HtmlHeaderFooter() { HtmlFragment = "<div style='text-align:right'><em style='color:pink'>page {page} of {total-pages}</em></div>" };

	var OutputPath = "HtmlToPDF.pdf";
	PDF.SaveAs(OutputPath);
	Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Screen;
}
Private Sub HTMLString()
	' Render any HTML fragment or document to HTML
	Dim Renderer = New IronPdf.HtmlToPdf()
	Dim PDF = Renderer.RenderHtmlAsPdf("<h1>Hello IronPDF</h1>")

	Renderer.PrintOptions.Footer = New HtmlHeaderFooter() With {.HtmlFragment = "<div style='text-align:right'><em style='color:pink'>page {page} of {total-pages}</em></div>"}

	Dim OutputPath = "HtmlToPDF.pdf"
	PDF.SaveAs(OutputPath)
	Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Screen
End Sub
Jump to Article
PDF from ASPX Page
protected void Page_Load(object sender, EventArgs e)
{
	IronPdf.AspxToPdf.RenderThisPageAsPdf();
}
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
	IronPdf.AspxToPdf.RenderThisPageAsPdf()
End Sub
Jump to Article
Response Viewport
using IronPdf;
IronPdf.HtmlToPdf Renderer = new IronPdf.HtmlToPdf();
 //Choose screen or print CSS media
Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Screen;
//Set the width of the responsive virtual browser window in pixels
Renderer.ViewPortWidth = 1280; 
// Render an HTML document or snippet as a string
Renderer.RenderHTMLFileAsPdf("Assets/Responsive.html");
Imports IronPdf
Private Renderer As New IronPdf.HtmlToPdf()
 'Choose screen or print CSS media
Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Screen
'Set the width of the responsive virtual browser window in pixels
Renderer.ViewPortWidth = 1280
' Render an HTML document or snippet as a string
Renderer.RenderHTMLFileAsPdf("Assets/Responsive.html")
Jump to Article
HTML Templates
var HtmlTemplate = "<p>[[NAME]]</p>";
var Names = new[] { "John", "James", "Jenny" };
foreach (var name in Names) {
    var HtmlInstance = HtmlTemplate.Replace("[[NAME]]", name);
    var Pdf = Renderer.RenderHtmlAsPdf(HtmlInstance);
    Pdf.SaveAs(name + ".pdf");
}
Dim HtmlTemplate = "<p>[[NAME]]</p>"
Dim Names = { "John", "James", "Jenny" }
For Each name In Names
	Dim HtmlInstance = HtmlTemplate.Replace("[[NAME]]", name)
	Dim Pdf = Renderer.RenderHtmlAsPdf(HtmlInstance)
	Pdf.SaveAs(name & ".pdf")
Next name
Jump to Article
Try IronPDF free for development


Overview

Any .NET developer will tell you that a lot of research goes into projects before starting with them. There is an old adage that says: use the right tool for the right job. PDF libraries are no exception to this rule. As a developer you have to be properly informed on which libraries and tools there are out there. Granted not all tools or libraries are created equal – some have different strengths than others, some have more weaknesses than others, but ultimately it is your perogative to use the tool that suits you and your company and most importantly, your project, most.

This article will compare two of the most popular PDF libraries for .NET and .NET Core developers. These two libraries are:

  • IronPDF
  • PDFSharp

With any comparison article, it is good to try and compare the good, the bad and the ugly whenever possible. Unfortunately, in the current technology landscape, some libraries fall quite short, whereas other libraries excel and thrive. Technology is moving at such a fast pace that it is difficult to remain current. Not only for third-party library creators, but for developers as well. Eat or be eaten and adapt very quickly.

Let's take a look at both offerings.

Get to Know IronPDF

IronPDF has comprehensive PDF editing and generation functionality via HTML to PDF. How does it work? Well, most of the document design and layout can use existing HTML and HTML5 assets.

IronPDF simplifies PDF tasks into easy to use and understand C# methods. This enhances developer productivity and speeds up development.

IronPDF is compatible with any .NET Framework project from Version 4 upwards and .NET Core from version 2 upwards.

IronPDF C# Library Features

Some great IronPDF features include:

  • Generating PDF documents from web platforms such as HTML and ASPX
  • Reading PDF text
  • Extracting images and data from PDF documents
  • Merging, splitting, and manipulating PDFs

Improvements in 2020 include:

  • Improved PDF text extraction accuracy
  • Added support for more PDF document types
  • Improved memory footprint
  • Digital signing of encrypted PDFs now supported
  • Digital signature metadata enhancements
  • Resolved edge case installation path & licensing issues
  • CentOS 8 and Ubuntu 20 support


Get to Know PDFSharp

PDFSharp is also a .NET library for processing PDF files. It creates PDF pages using drawing methods present in GDI+, which means that most of what GDI+ can do, PDFSharp can also do. Another component of PDFSharp is MigraDoc, which is a document generator. MigraDoc supports most word processor functionalities, where you can simply add tables, paragraphs, charts, bookmarks and breaks as needed.

PDFSharp and MigraDoc have an easy to understand object model to create documents and can be output in PDF, Word or HTML format.

PDFSharp has not had a production ready update since early 2019, the HTMLtoPDF third-party library has not been maintained since 2015, and it may be nearing end of life for support. PDFSharp is open source, and fixing code problems and bugs may take longer as it depends on separate contributions from developers in the open source landscape.

PDFSharp Read PDF, Print PDF & C# more features

  • Manipulate PDF documents
  • Merge PDFs
  • Split PDFs
  • Import data from various sources
  • Dynamic tables


Step 1: Installation

In this demonstration I initially wanted to show the power of both libraries by using a web project. Unfortunately, with PDFSharp not being geared up for proper web interfacing yet, it made current comparisons difficult. Instead I'll show some quick comparisons on a Windows Forms platform as well.

Start by Creating an ASP.NET Website

The next few steps create an ASP.NET Website

  • Open Visual Studio 2017 or Visual Studio 2019
  • Click File New Project to create a new project
  • Select Web under Visual C# in the Project type list box
  • Choose ASP.NET Web Application. This screenshot is shown next:

Figure 1New Project dialog box

  • Select OK
  • Choose Web Forms on the next screen as shown underneath

    Figure 2Web Forms

  • Click OK

Now, let’s Install IronPDF

1. Install IronPDF

There are two ways to install IronPDF:

  • NuGet
  • Download the library

Let’s have a closer look.

1.1. Install Library via NuGet

There are three ways to install IronPDF through NuGet, these are:

  • Visual Studio
  • Developer Command Prompt
  • Download the NuGet Package directly

Let’s have a look at them one-by-one.

1.2. Using Visual Studio

You access the NuGet Package Manager via the Project Menu, or by right clicking your project in the Solution Explorer.

Figure 3Project menu

Figure 4Right click Solution Explorer

After selected, browse for the IronPDF package and install it as shown next.

Figure 5Install IronPDF NuGet Package

1.3. Using Developer Command Prompt

Make use of the next few steps to install the IronPDF NuGet package via the Developer Command Prompt

  • Open Developer Command Prompt – found under the Visual Studio folder
  • Type: PM > Install-Package IronPdf
  • Press Enter
  • Reload your Visual Studio project

1.4. Download the NuGet Package directly

Make use of the next few steps to download the package through NuGet:

1.5. Install IronPDF by downloading the library

The second way to install IronPDF is by downloading it directly from the IronPDF DLL download

Figure 6Download IronPDF library

Reference the Library in your project by using the next steps:

  • Right click the Solution in the Solution Explorer
  • Select References
  • Browse for the IronPDF.dll library
  • Click OK


PDFSharp DLL C# Download

PDFSharp doesn’t inherently support web rendering (well, at least from what I can tell from hours and hours of web scarping for info), but with a separate third-party library (not from them), it is supposedly possible. I am not sure if the libraries should be updated or downgraded for it to work. Let me show you now.

HTML Renderer for PDFSharp

HTML Renderer is a separate third-party library that assists PDFSharp in converting HTML text or web pages into PDF.

Install PDFSharp with NuGet

There are three ways to install the iTextSharp NuGet package, they are:

  • Visual Studio
  • Developer Command Prompt
  • Download the NuGet Package directly

Let’s do them one-by-one.

For Visual Studio, search for PDFSharp and install the relevant packages, as shown next.

Figure 7PDFSharp

Or, in the Developer Command Prompt (as shown previously, enter the following command)

  • PM > Install-Package PDFSharp

Or, download it directly from the following options

PDFSharp website: http://www.pdfsharp.net/Downloads.ashx

PDFSharp SourceForge: https://sourceforge.net/projects/pdfsharp/files/

PDFSharp CodePlex: https://archive.codeplex.com/?p=pdfsharp

PDFSharp GitHub: https://github.com/empira/PDFsharp

Figure 8PDFSharp Download Options

Then follow the above steps again to install HTMLRenderer.PDFSharp

Now that you have created the necessary projects, let us attempt compare these two libraries in code.


How to Tutorial

2. Create PDF from HTML Text Input

The next code creates a PDF document and prints an HTML string inside it.

2.1. HTML String to PDF with IronPDF

The following code is using IronPDF to create a PDF document directly from an HTML string.

private void HTMLString()
{
    // Render any HTML fragment or document to HTML
    var Renderer = new IronPdf.HtmlToPdf();
    var PDF = Renderer.RenderHtmlAsPdf("<h1>Hello IronPDF</h1>");

    Renderer.PrintOptions.Footer = new HtmlHeaderFooter() { HtmlFragment = "<div style='text-align:right'><em style='color:pink'>page {page} of {total-pages}</em></div>" };

    var OutputPath = "HtmlToPDF.pdf";
    PDF.SaveAs(OutputPath);
    Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Screen;
}
private void HTMLString()
{
    // Render any HTML fragment or document to HTML
    var Renderer = new IronPdf.HtmlToPdf();
    var PDF = Renderer.RenderHtmlAsPdf("<h1>Hello IronPDF</h1>");

    Renderer.PrintOptions.Footer = new HtmlHeaderFooter() { HtmlFragment = "<div style='text-align:right'><em style='color:pink'>page {page} of {total-pages}</em></div>" };

    var OutputPath = "HtmlToPDF.pdf";
    PDF.SaveAs(OutputPath);
    Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Screen;
}
Private Sub HTMLString()
	' Render any HTML fragment or document to HTML
	Dim Renderer = New IronPdf.HtmlToPdf()
	Dim PDF = Renderer.RenderHtmlAsPdf("<h1>Hello IronPDF</h1>")

	Renderer.PrintOptions.Footer = New HtmlHeaderFooter() With {.HtmlFragment = "<div style='text-align:right'><em style='color:pink'>page {page} of {total-pages}</em></div>"}

	Dim OutputPath = "HtmlToPDF.pdf"
	PDF.SaveAs(OutputPath)
	Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Screen
End Sub
VB   C#

2.2. HTML String to PDF with PDFSharp

The following code uses HTMLRenderer to create a PDF document directly from HTML text.

protected void Page_Load(object sender, EventArgs e)
{
    SaveHTMLOnly();
}
protected void Page_Load(object sender, EventArgs e)
{
    SaveHTMLOnly();
}
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
	SaveHTMLOnly()
End Sub
VB   C#
private static Byte[] HTMLString(String html)
{
    Byte[] res = null;
    using (MemoryStream ms = new MemoryStream())
    {
        var pdf = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf("text", PdfSharp.PageSize.A4);

        pdf.Save(ms);
        res = ms.ToArray();
    }
    return res;
}
private static Byte[] HTMLString(String html)
{
    Byte[] res = null;
    using (MemoryStream ms = new MemoryStream())
    {
        var pdf = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf("text", PdfSharp.PageSize.A4);

        pdf.Save(ms);
        res = ms.ToArray();
    }
    return res;
}
Private Shared Function HTMLString(ByVal html As String) As Byte()
	Dim res() As Byte = Nothing
	Using ms As New MemoryStream()
		Dim pdf = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf("text", PdfSharp.PageSize.A4)

		pdf.Save(ms)
		res = ms.ToArray()
	End Using
	Return res
End Function
VB   C#
protected void Page_Load(object sender, EventArgs e)
{
    private void SaveHTMLOnly()
    {
        Byte[] fileContent = HTMLString("<h1>Hello PDFSharp</h1>");
        string fileName = "PDFSharp_HTMLOnly.pdf";
        string[] stringParts = fileName.Split(new char[] { '.' });
        string strType = stringParts[1];
        Response.Clear();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
        //Set the content type as file extension type
        Response.ContentType = strType;
        //Write the file content
        this.Response.BinaryWrite(fileContent);
        this.Response.End();
    }
}
protected void Page_Load(object sender, EventArgs e)
{
    private void SaveHTMLOnly()
    {
        Byte[] fileContent = HTMLString("<h1>Hello PDFSharp</h1>");
        string fileName = "PDFSharp_HTMLOnly.pdf";
        string[] stringParts = fileName.Split(new char[] { '.' });
        string strType = stringParts[1];
        Response.Clear();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
        //Set the content type as file extension type
        Response.ContentType = strType;
        //Write the file content
        this.Response.BinaryWrite(fileContent);
        this.Response.End();
    }
}
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'	private void SaveHTMLOnly()
'	{
'		Byte[] fileContent = HTMLString("<h1>Hello PDFSharp</h1>");
'		string fileName = "PDFSharp_HTMLOnly.pdf";
'		string[] stringParts = fileName.Split(New char[] { "."c });
'		string strType = stringParts[1];
'		Response.Clear();
'		Response.ClearContent();
'		Response.ClearHeaders();
'		Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
'		'Set the content type as file extension type
'		Response.ContentType = strType;
'		'Write the file content
'		Me.Response.BinaryWrite(fileContent);
'		Me.Response.@End();
'	}
End Sub
VB   C#

2.3. HTML String Code Comparison

Both code segments look short and easy to understand, but, the PDFSharp code segment is not working as it should. This may be due to the fact that there is no maintenance being done on the library to update it so that it can work with modern technologies. The following are a few website addresses that cover the HTML rendering of this library and why it might not work:


3. ASPX Pages to PDF

The next code creates a PDF document from an ASPX page.

3.1. ASPX Pages to PDF with IronPDF

The following code makes use of IronPDF to create a PDF containing from an ASPX file.

protected void Page_Load(object sender, EventArgs e)
{
    IronPdf.AspxToPdf.RenderThisPageAsPdf();
}
protected void Page_Load(object sender, EventArgs e)
{
    IronPdf.AspxToPdf.RenderThisPageAsPdf();
}
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
	IronPdf.AspxToPdf.RenderThisPageAsPdf()
End Sub
VB   C#

3.2. ASPX Pages to PDF with PDFSharp

It seems as if PDF does not support creating PDFs from ASPX web pages.


4. Using CSS3 with PDF Documents

HTML to PDF Supports:

  • Full and high-fidelity HTML 4 and HTML 5 rendering
  • CSS 3
  • JavaScript
  • Image assets
  • SVG assets
  • Responsive layouts
  • External stylesheets and assets (http https or filesystem)
  • Static and multithreaded rendering
  • Loading URLS using with custom:
    • Network login credentials
    • UserAgents
    • Proxies
    • Cookies
    • HTTP headers
    • Form variables allowing login behind HTML login forms

4.1. Cascading Style Sheets CSS3

Cascading Style Sheets (CSS) describes the look and formatting of an HTML document. It makes use of selectors and properties to set the formatting of an entire web page or website at one central place. CSS3 is a latest standard. CSS3 includes:

  • Media Queries
  • Namespaces
  • Selectors Level 3
  • Modules including:
    • Selectors
    • Box Model
    • Text Effects
    • 2D Transformations
    • 3D Transformations
    • Backgrounds
    • User Interface

With IronPDF you have a choice where you’d like the CSS styles to render to. Screen or Print. When dealing with the screen, you have to know about Responsiveness (which I will delve into a bit later). To distinguish between the screen or printer, you could use the following quick line of code:

Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Print
//or
Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Screen
Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Print
//or
Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Screen
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Print Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Screen
VB   C#

4.2. Responsive Web Design

Responsive web design ensures web pages and websites that look good on all devices. Responsive webs automatically adjust according to different screen sizes and viewports. While working with responsive design and frameworks such as Bootstrap, IronPDF can set the ViewPortWidth and ViewPortHeight properties to programmatically control the viewport and control which version of the responsive site to render as a PDF.

4.3. Creating a Response ViewPort

The following code allows you to programmatically set the size of your response Viewport with IronPDF.

using IronPdf;
IronPdf.HtmlToPdf Renderer = new IronPdf.HtmlToPdf();
 //Choose screen or print CSS media
Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Screen;
//Set the width of the responsive virtual browser window in pixels
Renderer.ViewPortWidth = 1280; 
// Render an HTML document or snippet as a string
Renderer.RenderHTMLFileAsPdf("Assets/Responsive.html");
using IronPdf;
IronPdf.HtmlToPdf Renderer = new IronPdf.HtmlToPdf();
 //Choose screen or print CSS media
Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Screen;
//Set the width of the responsive virtual browser window in pixels
Renderer.ViewPortWidth = 1280; 
// Render an HTML document or snippet as a string
Renderer.RenderHTMLFileAsPdf("Assets/Responsive.html");
Imports IronPdf
Private Renderer As New IronPdf.HtmlToPdf()
 'Choose screen or print CSS media
Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Screen
'Set the width of the responsive virtual browser window in pixels
Renderer.ViewPortWidth = 1280
' Render an HTML document or snippet as a string
Renderer.RenderHTMLFileAsPdf("Assets/Responsive.html")
VB   C#

4.4. HTML Templates

Another awesome feature of PDF for HTML is the ability to create HTML templates from which to work from and build similar PDF documents. Here is a small example:

var HtmlTemplate = "<p>[[NAME]]</p>";
var Names = new[] { "John", "James", "Jenny" };
foreach (var name in Names) {
    var HtmlInstance = HtmlTemplate.Replace("[[NAME]]", name);
    var Pdf = Renderer.RenderHtmlAsPdf(HtmlInstance);
    Pdf.SaveAs(name + ".pdf");
}
var HtmlTemplate = "<p>[[NAME]]</p>";
var Names = new[] { "John", "James", "Jenny" };
foreach (var name in Names) {
    var HtmlInstance = HtmlTemplate.Replace("[[NAME]]", name);
    var Pdf = Renderer.RenderHtmlAsPdf(HtmlInstance);
    Pdf.SaveAs(name + ".pdf");
}
Dim HtmlTemplate = "<p>[[NAME]]</p>"
Dim Names = { "John", "James", "Jenny" }
For Each name In Names
	Dim HtmlInstance = HtmlTemplate.Replace("[[NAME]]", name)
	Dim Pdf = Renderer.RenderHtmlAsPdf(HtmlInstance)
	Pdf.SaveAs(name & ".pdf")
Next name
VB   C#

Here, you loop through the Names array (John, James and Jenny) and create similar and personalised content for each person.


5. Compare on Windows Forms

Because a decent comparison between PDFSharp and IronPDF could not be made on a web platform, let’s quickly see how they compare on a Windows platform.

Creating a simple ‘Hello World’ Application using both libraries.

A simple application using PDFSharp looks like the following:

using System.Diagnostics;
using PdfSharp.Drawing;
using PdfSharp.Pdf;

namespace HelloWorld
{
    /// <summary>
    /// This sample is the obligatory Hello World program.
    /// </summary>
    class Program
    {
        static void Main()
        {
            // Create a new PDF document.
            var document = new PdfDocument();
            document.Info.Title = "Created with PDFsharp";

            // Create an empty page in this document.
            var page = document.AddPage();

            // Get an XGraphics object for drawing on this page.
            var gfx = XGraphics.FromPdfPage(page);

            // Draw two lines with a red default pen.
            var width = page.Width;
            var height = page.Height;
            gfx.DrawLine(XPens.Red, 0, 0, width, height);
            gfx.DrawLine(XPens.Red, width, 0, 0, height);

            // Draw a circle with a red pen which is 1.5 point thick.
            var r = width / 5;
            gfx.DrawEllipse(new XPen(XColors.Red, 1.5), XBrushes.White, new XRect(width / 2 - r, height / 2 - r, 2 * r, 2 * r));

            // Create a font.
            var font = new XFont("Times New Roman", 20, XFontStyle.BoldItalic);

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

            // Save the document...
            const string filename = "HelloWorld_tempfile.pdf";
            document.Save(filename);
            // ...and start a viewer.
            Process.Start(filename);
        }
    }
}
using System.Diagnostics;
using PdfSharp.Drawing;
using PdfSharp.Pdf;

namespace HelloWorld
{
    /// <summary>
    /// This sample is the obligatory Hello World program.
    /// </summary>
    class Program
    {
        static void Main()
        {
            // Create a new PDF document.
            var document = new PdfDocument();
            document.Info.Title = "Created with PDFsharp";

            // Create an empty page in this document.
            var page = document.AddPage();

            // Get an XGraphics object for drawing on this page.
            var gfx = XGraphics.FromPdfPage(page);

            // Draw two lines with a red default pen.
            var width = page.Width;
            var height = page.Height;
            gfx.DrawLine(XPens.Red, 0, 0, width, height);
            gfx.DrawLine(XPens.Red, width, 0, 0, height);

            // Draw a circle with a red pen which is 1.5 point thick.
            var r = width / 5;
            gfx.DrawEllipse(new XPen(XColors.Red, 1.5), XBrushes.White, new XRect(width / 2 - r, height / 2 - r, 2 * r, 2 * r));

            // Create a font.
            var font = new XFont("Times New Roman", 20, XFontStyle.BoldItalic);

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

            // Save the document...
            const string filename = "HelloWorld_tempfile.pdf";
            document.Save(filename);
            // ...and start a viewer.
            Process.Start(filename);
        }
    }
}
Imports System.Diagnostics
Imports PdfSharp.Drawing
Imports PdfSharp.Pdf

Namespace HelloWorld
	''' <summary>
	''' This sample is the obligatory Hello World program.
	''' </summary>
	Friend Class Program
		Shared Sub Main()
			' Create a new PDF document.
			Dim document = New PdfDocument()
			document.Info.Title = "Created with PDFsharp"

			' Create an empty page in this document.
			Dim page = document.AddPage()

			' Get an XGraphics object for drawing on this page.
			Dim gfx = XGraphics.FromPdfPage(page)

			' Draw two lines with a red default pen.
			Dim width = page.Width
			Dim height = page.Height
			gfx.DrawLine(XPens.Red, 0, 0, width, height)
			gfx.DrawLine(XPens.Red, width, 0, 0, height)

			' Draw a circle with a red pen which is 1.5 point thick.
			Dim r = width \ 5
			gfx.DrawEllipse(New XPen(XColors.Red, 1.5), XBrushes.White, New XRect(width \ 2 - r, height \ 2 - r, 2 * r, 2 * r))

			' Create a font.
			Dim font = New XFont("Times New Roman", 20, XFontStyle.BoldItalic)

			' Draw the text.
			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_tempfile.pdf"
			document.Save(filename)
			' ...and start a viewer.
			Process.Start(filename)
		End Sub
	End Class
End Namespace
VB   C#

For a complete set of PDFSharp samples, specifically for Windows based apps, please check out the PDFSharp documentation.


Licensing

6. Licensing Options

PDFSharp is Open Source and completely free to use. This means that you can copy and modify PDFSharp’s code into your code without any restrictions. However, this also comes with the fact that it has not been updated in a number of years and with free software support is often limited.

IronPDF is an openly commercial C# PDF library. It is free for development, with 30-day deployment trials available by emailing the engineering team at developers@ironpdf.com. Affordable licensing options can be found by exploring the IronPDF Licenses.


Tutorial Quick Access

Explore the IronPDF Object Reference

Explore the Object Reference for IronPDF C# Library, including details of all of IronPDF’s features, classes, method fields, namespaces, and enums.

View the Object Reference