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.


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 recently. Its ChromePdfRenderer 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

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, but with a separate third-party library (not from them), it is supposedly possible.

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 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.

/**
PDF from HTML String
anchor-html-string-to-pdf-with-ironpdf
**/
private void HTMLString()
{
    // Render any HTML fragment or document to HTML
    var Renderer = new IronPdf.ChromePdfRenderer();
    using var PDF = Renderer.RenderHtmlAsPdf("<h1>Hello IronPDF</h1>");

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

    var OutputPath = "ChromePdfRenderer.pdf";
    PDF.SaveAs(OutputPath);
    Renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Screen;
}
/**
PDF from HTML String
anchor-html-string-to-pdf-with-ironpdf
**/
private void HTMLString()
{
    // Render any HTML fragment or document to HTML
    var Renderer = new IronPdf.ChromePdfRenderer();
    using var PDF = Renderer.RenderHtmlAsPdf("<h1>Hello IronPDF</h1>");

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

    var OutputPath = "ChromePdfRenderer.pdf";
    PDF.SaveAs(OutputPath);
    Renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Screen;
}
'''
'''PDF from HTML String
'''anchor-html-string-to-pdf-with-ironpdf
'''*
Private Sub HTMLString()
	' Render any HTML fragment or document to HTML
	Dim Renderer = New IronPdf.ChromePdfRenderer()
	Dim PDF = Renderer.RenderHtmlAsPdf("<h1>Hello IronPDF</h1>")

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

	Dim OutputPath = "ChromePdfRenderer.pdf"
	PDF.SaveAs(OutputPath)
	Renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.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:

2.4. URL to PDF Comparison

In this section, we will compare how PDFSharp and IronPDF converts a web page (by URL) into a PDF.

Rendering Quality

The images below shows the results generated from both IronPDF and PDFSharp when converting the Apple website's homepage into PDF.

IronPDF Output

IronPDF Output

PDFSharp Output

PDFSharp Output

IronPDF renders webpages comparatively better than PDFSharp does. PDFSharp renders images in poorer quality, and conversion from URL takes a lot longer. Conversely, IronPDF has amazing and performant rendering quality.

Code Quality

Next, we will now compare the source code that we used to generate the PDF output shown in the previous section.

IronPDF Code
using IronPdf;
// Instantiate Renderer
var Renderer = new IronPdf.ChromePdfRenderer();
Renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A2;
//HTML String to PDF
using var pdf = Renderer.RenderUrlAsPdf("https://www.apple.com/");
//Choose Screen or Print CSS media
Renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Screen;
//Set the width of the responsive virtual browser window in pixels
Renderer.RenderingOptions.ViewPortWidth = 1280;
// Export to a file or Stream
pdf.SaveAs("Apple.pdf");
using IronPdf;
// Instantiate Renderer
var Renderer = new IronPdf.ChromePdfRenderer();
Renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A2;
//HTML String to PDF
using var pdf = Renderer.RenderUrlAsPdf("https://www.apple.com/");
//Choose Screen or Print CSS media
Renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Screen;
//Set the width of the responsive virtual browser window in pixels
Renderer.RenderingOptions.ViewPortWidth = 1280;
// Export to a file or Stream
pdf.SaveAs("Apple.pdf");
Imports IronPdf
' Instantiate Renderer
Private Renderer = New IronPdf.ChromePdfRenderer()
Renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A2
'HTML String to PDF
Dim pdf = Renderer.RenderUrlAsPdf("https://www.apple.com/")
'Choose Screen or Print CSS media
Renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Screen
'Set the width of the responsive virtual browser window in pixels
Renderer.RenderingOptions.ViewPortWidth = 1280
' Export to a file or Stream
pdf.SaveAs("Apple.pdf")
VB   C#
PDFSharp Code
using PdfSharp;
using PdfSharp.Pdf;
using System;
using System.IO;
using System.Net;
using TheArtOfDev.HtmlRenderer.PdfSharp;

namespace PDFSharp
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Create request for given url
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://apple.com");

            //Create response-object
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            //Take response stream
            StreamReader sr = new StreamReader(response.GetResponseStream());

            //Read response stream (html code)
            string htmlString = sr.ReadToEnd();

            //Close streamreader and response
            sr.Close();
            response.Close();

            PdfDocument pdfDocument = PdfGenerator.GeneratePdf(htmlString, PageSize.A4);
            pdfDocument.Save("C:/File/HTML to PDF Document.pdf");
        }
    }
}
using PdfSharp;
using PdfSharp.Pdf;
using System;
using System.IO;
using System.Net;
using TheArtOfDev.HtmlRenderer.PdfSharp;

namespace PDFSharp
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Create request for given url
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://apple.com");

            //Create response-object
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            //Take response stream
            StreamReader sr = new StreamReader(response.GetResponseStream());

            //Read response stream (html code)
            string htmlString = sr.ReadToEnd();

            //Close streamreader and response
            sr.Close();
            response.Close();

            PdfDocument pdfDocument = PdfGenerator.GeneratePdf(htmlString, PageSize.A4);
            pdfDocument.Save("C:/File/HTML to PDF Document.pdf");
        }
    }
}
Imports PdfSharp
Imports PdfSharp.Pdf
Imports System
Imports System.IO
Imports System.Net
Imports TheArtOfDev.HtmlRenderer.PdfSharp

Namespace PDFSharp
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			'Create request for given url
			Dim request As HttpWebRequest = CType(HttpWebRequest.Create("https://apple.com"), HttpWebRequest)

			'Create response-object
			Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)

			'Take response stream
			Dim sr As New StreamReader(response.GetResponseStream())

			'Read response stream (html code)
			Dim htmlString As String = sr.ReadToEnd()

			'Close streamreader and response
			sr.Close()
			response.Close()

			Dim pdfDocument As PdfDocument = PdfGenerator.GeneratePdf(htmlString, PageSize.A4)
			pdfDocument.Save("C:/File/HTML to PDF Document.pdf")
		End Sub
	End Class
End Namespace
VB   C#

Using PDFSharp to generate PDFs from a web page typically requires long and complex boilerplate code. As shown in the last code example, we must make use of many functions from different packages. As PDFSharp doesn’t support direct URLs, you need to download the source code of the URL first, then pass it to the GeneratePdf function. On the other hand, IronPDF can accomplish the same task with one call its renderUrlAsPdf method.

The first code example shows that IronPDF provides an array of convenient properties and methods for styling PDF documents (pre and post rendering). We can use HTML and CSS to set custom colors, borders, background, etc. Accomplishing similar feats with PDFSharp requires the use of complex methods and classes which can be quite difficult to use.

CSS and Javascript Support

PDFSharp has no support for CSS and JavaScript, which means that it is not compatible with the latest technologies. This makes PDFSharp virtually obsolete. On the other hand, IronPDF has full support for CSS and JavaScript. We can style PDF output easily using custom CSS rules. IronPDF also provides a function for enabling and disable JavaScript interpretation/execution during PDF conversion. This increases the quality of the PDF file output.

Dependencies

PDFSharp requires two packages to work properly: System.Drawing.Common and System.Text.Encoding.CodePages. It also leverages the HtmlRenderer add-on to convert HTML pages to PDF files.

PDFSharp vs IronPDF: PDFSharp Dependencies

IronPDF doesn’t require the use of extra libraries, making it lightweight and easy to use.

Compatibility

PDFSharp is an outdated library. It has not been updated for several years, which is why it is incompatible with most technologies such as Azure, Docker, AWS, etc.

IronPDF is updated frequently to make the rendering process easier and more advanced. IronPDF is compatible with all the latest .NET technologies such as Azure, Docker, AWS, etc. It is also compatible with all operating systems, including Windows, macOS, Ubuntu, etc.


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.

/**
PDF from ASPX Page
anchor-aspx-pages-to-pdf-with-ironpdf
**/
protected void Page_Load(object sender, EventArgs e)
{
    IronPdf.AspxToPdf.RenderThisPageAsPdf();
}
/**
PDF from ASPX Page
anchor-aspx-pages-to-pdf-with-ironpdf
**/
protected void Page_Load(object sender, EventArgs e)
{
    IronPdf.AspxToPdf.RenderThisPageAsPdf();
}
'''
'''PDF from ASPX Page
'''anchor-aspx-pages-to-pdf-with-ironpdf
'''*
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. To distinguish between the screen or printer, you could use the following quick line of code:

Renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print
//or
Renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Screen
Renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print
//or
Renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Screen
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print Renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.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.

/**
Response Viewport
anchor-creating-a-response-viewport
**/
using IronPdf;
IronPdf.ChromePdfRenderer Renderer = new IronPdf.ChromePdfRenderer();
 //Choose screen or print CSS media
Renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.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");
/**
Response Viewport
anchor-creating-a-response-viewport
**/
using IronPdf;
IronPdf.ChromePdfRenderer Renderer = new IronPdf.ChromePdfRenderer();
 //Choose screen or print CSS media
Renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.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");
'''
'''Response Viewport
'''anchor-creating-a-response-viewport
'''*
Imports IronPdf
Private Renderer As New IronPdf.ChromePdfRenderer()
 'Choose screen or print CSS media
Renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.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:

/**
HTML Templates
anchor-html-templates
**/
var HtmlTemplate = "<p>[[NAME]]</p>";
var Names = new[] { "John", "James", "Jenny" };
foreach (var name in Names) {
    var HtmlInstance = HtmlTemplate.Replace("[[NAME]]", name);
    using var Pdf = Renderer.RenderHtmlAsPdf(HtmlInstance);
    Pdf.SaveAs(name + ".pdf");
}
/**
HTML Templates
anchor-html-templates
**/
var HtmlTemplate = "<p>[[NAME]]</p>";
var Names = new[] { "John", "James", "Jenny" };
foreach (var name in Names) {
    var HtmlInstance = HtmlTemplate.Replace("[[NAME]]", name);
    using var Pdf = Renderer.RenderHtmlAsPdf(HtmlInstance);
    Pdf.SaveAs(name + ".pdf");
}
'''
'''HTML Templates
'''anchor-html-templates
'''*
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.

7. Summary

IronPDF is a supported, productivity-first .NET library to:

  • Render PDFs from HTML using a fully embedded web browser
  • Edit and manipulate PDFs
  • Digitally Sign PDFs

PdfSharp is a free but somewhat unsupported .NET library to:

  • Create and edit PDFs by manually drawing shapes and text to page objects.

Tutorial Quick Access

Explore the IronPDF API Reference

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

View the API Reference