Skip to footer content
PRODUCT COMPARISONS

PDFsharp Sign PDF documents Digitally vs IronPDF (Code Example)

A digital signature is a mathematical technique that verifies the authenticity and integrity of an electronic document. It serves as an electronic signature to digitally sign documents in several jurisdictions, ensuring great security and legal validity.

Digital signatures are created using a private key, which is only known to the signer. This private key establishes a unique digital signature linked to the document when it is signed. The signature includes the signer's name, email address, and other personal information. To confirm a digitally signed document's authenticity, the recipient requires access to the signer's public key. The signature's legitimacy is verified by decrypting it using the public key.

In this tutorial, we compare how to add digital signatures to PDF documents using PDFSharp and IronPDF. Digital signatures are essential for verifying document authenticity, and PDF files are a popular format for such operations.

PDFsharp is a well-known open-source library for PDF creation and manipulation, while IronPDF is a robust .NET PDF library offering similar features with additional advanced functionalities.

This guide covers signing a PDF document with a private key and verifying the signature, along with example source code for both libraries.

Why Are Digital Signatures Important?

Digital signatures ensure document integrity and offer robust security. They are commonly used for contracts, agreements, and other legal documents.

Key benefits:

  • More secure and tamper-proof than traditional signatures.
  • Verified electronically, reducing manual verification efforts.
  • Enable remote signing of documents globally.
  • Provide greater assurance than traditional signatures.

PDFsharp Overview

PDFSharp is an open-source C# library primarily designed for creating and manipulating PDF documents. It is widely used for basic PDF tasks, such as generating simple PDF files, editing existing documents, and rendering graphics. However, its native support for advanced features like digital signatures is limited, and developers often need to rely on third-party libraries, such as BouncyCastle, to integrate such functionalities. PDFsharp is open-source, under the MIT License, making it a good choice for projects where cost and flexibility are a priority.

Key Features

  • Open-source and free under the MIT License.
  • Basic PDF creation and manipulation.
  • Can be extended with external libraries like BouncyCastle for digital signatures.
  • Lacks out-of-the-box support for advanced PDF features such as HTML-to-PDF conversion and complex form handling.

IronPDF Overview

PDFsharp Sign PDF documents Digitally vs IronPDF (Code Example): Figure 1 - image.png

IronPDF is a robust .NET PDF library that provides a simple and powerful API for generating, editing, and manipulating PDFs. One of its standout features is the ease with which developers can implement digital signatures, which are essential for verifying document authenticity. In addition to digital signatures, IronPDF supports advanced functionalities such as HTML-to-PDF conversion, watermarking, and form handling. It is especially valuable for developers working on commercial projects where rapid implementation and robust features are a priority.

Key Features

  • Commercial license with paid support, and a free trial available.
  • Easy-to-use API with modern features for digital signing and document manipulation.
  • Includes built-in support for HTML-to-PDF format conversion, form handling, and PDF annotations (such as attachment annotations).
  • Seamless integration with advanced functionalities like timestamping, visual signature images, and encryption.

Adding a Digital Signature Programmatically with PDFsharp

PDFsharp is an open-source library designed for PDF creation and manipulation in C#. However, while it does offer support to add a signature, you’ll need to integrate a third-party tool like BouncyCastle to ensure secure, accurate digital signing of PDF documents.

Steps to Add a Digital Signature with PDFsharp

  1. Install PDFsharp and BouncyCastle via NuGet.
  2. Create a digital certificate using X509Certificate2.
  3. Sign the PDF with BouncyCastle.

Example Code

using System;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using BouncyCastleSigner; // Hypothetical namespace for illustration
// Ensure that you have the appropriate namespaces added

class Program
{
    static void Main(string[] args)
    {
        // Create a font for the appearance of the signature
        var font = new XFont("Verdana", 10.0, XFontStyle.Regular);

        // Create a new PDF document
        var document = new PdfDocument();
        var pdfPage = document.AddPage();

        // Prepare graphics for drawing on the PDF page
        var xGraphics = XGraphics.FromPdfPage(pdfPage);
        var layoutRectangle = new XRect(0.0, 0.0, pdfPage.Width.Point, pdfPage.Height.Point);

        // Add some text to the page
        xGraphics.DrawString("Signed sample document", font, XBrushes.Black, layoutRectangle, XStringFormats.TopCenter);

        // Define digital signature appearance options
        var options = new DigitalSignatureOptions
        {
            ContactInfo = "John Doe",
            Location = "Seattle",
            Reason = "License Agreement",
            Rectangle = new XRect(36.0, 700.0, 400.0, 50.0),
            AppearanceHandler = new SignatureAppearanceHandler()
        };

        // Sign the document using BouncyCastle signer
        var pdfSignatureHandler = DigitalSignatureHandler.ForDocument(document,
            new PdfSharp.Snippets.Pdf.BouncyCastleSigner(GetCertificate(), PdfMessageDigestType.SHA256), options);

        // Save the signed document
        document.Save("PdfSharpSignature.pdf");
    }

    static (X509Certificate2, X509Certificate2Collection) GetCertificate()
    {
        // Locate the certificate file and read its data
        var certFolder = "C:\\Users\\kyess\\AppData\\Roaming\\Adobe\\Acrobat\\DC\\Security";
        var pfxFile = Path.Combine(certFolder, "IronSoftware.pfx");
        var rawData = File.ReadAllBytes(pfxFile);

        // Load the certificate using its password (example password)
        var certificatePassword = "Passw0rd";
        var certificate = new X509Certificate2(rawData, certificatePassword,
            X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

        // Create and return the certificate collection
        var collection = new X509Certificate2Collection();
        collection.Import(rawData, certificatePassword,
            X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
        return (certificate, collection);
    }
}
using System;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using BouncyCastleSigner; // Hypothetical namespace for illustration
// Ensure that you have the appropriate namespaces added

class Program
{
    static void Main(string[] args)
    {
        // Create a font for the appearance of the signature
        var font = new XFont("Verdana", 10.0, XFontStyle.Regular);

        // Create a new PDF document
        var document = new PdfDocument();
        var pdfPage = document.AddPage();

        // Prepare graphics for drawing on the PDF page
        var xGraphics = XGraphics.FromPdfPage(pdfPage);
        var layoutRectangle = new XRect(0.0, 0.0, pdfPage.Width.Point, pdfPage.Height.Point);

        // Add some text to the page
        xGraphics.DrawString("Signed sample document", font, XBrushes.Black, layoutRectangle, XStringFormats.TopCenter);

        // Define digital signature appearance options
        var options = new DigitalSignatureOptions
        {
            ContactInfo = "John Doe",
            Location = "Seattle",
            Reason = "License Agreement",
            Rectangle = new XRect(36.0, 700.0, 400.0, 50.0),
            AppearanceHandler = new SignatureAppearanceHandler()
        };

        // Sign the document using BouncyCastle signer
        var pdfSignatureHandler = DigitalSignatureHandler.ForDocument(document,
            new PdfSharp.Snippets.Pdf.BouncyCastleSigner(GetCertificate(), PdfMessageDigestType.SHA256), options);

        // Save the signed document
        document.Save("PdfSharpSignature.pdf");
    }

    static (X509Certificate2, X509Certificate2Collection) GetCertificate()
    {
        // Locate the certificate file and read its data
        var certFolder = "C:\\Users\\kyess\\AppData\\Roaming\\Adobe\\Acrobat\\DC\\Security";
        var pfxFile = Path.Combine(certFolder, "IronSoftware.pfx");
        var rawData = File.ReadAllBytes(pfxFile);

        // Load the certificate using its password (example password)
        var certificatePassword = "Passw0rd";
        var certificate = new X509Certificate2(rawData, certificatePassword,
            X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

        // Create and return the certificate collection
        var collection = new X509Certificate2Collection();
        collection.Import(rawData, certificatePassword,
            X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
        return (certificate, collection);
    }
}
Imports System
Imports System.IO
Imports System.Security.Cryptography.X509Certificates
Imports PdfSharp.Drawing
Imports PdfSharp.Pdf
Imports BouncyCastleSigner ' Hypothetical namespace for illustration
' Ensure that you have the appropriate namespaces added

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Create a font for the appearance of the signature
		Dim font = New XFont("Verdana", 10.0, XFontStyle.Regular)

		' Create a new PDF document
		Dim document = New PdfDocument()
		Dim pdfPage = document.AddPage()

		' Prepare graphics for drawing on the PDF page
		Dim xGraphics = XGraphics.FromPdfPage(pdfPage)
		Dim layoutRectangle = New XRect(0.0, 0.0, pdfPage.Width.Point, pdfPage.Height.Point)

		' Add some text to the page
		xGraphics.DrawString("Signed sample document", font, XBrushes.Black, layoutRectangle, XStringFormats.TopCenter)

		' Define digital signature appearance options
		Dim options = New DigitalSignatureOptions With {
			.ContactInfo = "John Doe",
			.Location = "Seattle",
			.Reason = "License Agreement",
			.Rectangle = New XRect(36.0, 700.0, 400.0, 50.0),
			.AppearanceHandler = New SignatureAppearanceHandler()
		}

		' Sign the document using BouncyCastle signer
		Dim pdfSignatureHandler = DigitalSignatureHandler.ForDocument(document, New PdfSharp.Snippets.Pdf.BouncyCastleSigner(GetCertificate(), PdfMessageDigestType.SHA256), options)

		' Save the signed document
		document.Save("PdfSharpSignature.pdf")
	End Sub

	Private Shared Function GetCertificate() As (X509Certificate2, X509Certificate2Collection)
		' Locate the certificate file and read its data
		Dim certFolder = "C:\Users\kyess\AppData\Roaming\Adobe\Acrobat\DC\Security"
		Dim pfxFile = Path.Combine(certFolder, "IronSoftware.pfx")
		Dim rawData = File.ReadAllBytes(pfxFile)

		' Load the certificate using its password (example password)
		Dim certificatePassword = "Passw0rd"
		Dim certificate = New X509Certificate2(rawData, certificatePassword, X509KeyStorageFlags.MachineKeySet Or X509KeyStorageFlags.PersistKeySet Or X509KeyStorageFlags.Exportable)

		' Create and return the certificate collection
		Dim collection = New X509Certificate2Collection()
		collection.Import(rawData, certificatePassword, X509KeyStorageFlags.MachineKeySet Or X509KeyStorageFlags.PersistKeySet Or X509KeyStorageFlags.Exportable)
		Return (certificate, collection)
	End Function
End Class
$vbLabelText   $csharpLabel

Output

PDFsharp Sign PDF documents Digitally vs IronPDF (Code Example): Figure 2

As you can see here, while it was able to create a digital signature field and apply the certificate to our new document, the process is extensive, manual, and not overly efficient to implement when compared to libraries such as IronPDF.

Adding a Digital Signature with IronPDF

IronPDF provides developers with a concise method for digitally signing PDF documents.

using IronPdf;
using System.Security.Cryptography.X509Certificates;

public class Program
{
    static void Main(string[] args)
    {
        // Load the certificate with its password
        var sig = new PdfSignature("IronSoftware.pfx", "your-password");

        // Configure additional signature details
        sig.TimestampHashAlgorithm = TimestampHashAlgorithms.SHA256;
        sig.TimestampUrl = "http://timestamp.digicert.com";
        sig.SignatureImage = new PdfSignatureImage("IronPdf.png", 0, new Rectangle(150, 100, 200, 200));

        // Sign and save the PDF document
        sig.SignPdfFile("output.pdf");
    }
}
using IronPdf;
using System.Security.Cryptography.X509Certificates;

public class Program
{
    static void Main(string[] args)
    {
        // Load the certificate with its password
        var sig = new PdfSignature("IronSoftware.pfx", "your-password");

        // Configure additional signature details
        sig.TimestampHashAlgorithm = TimestampHashAlgorithms.SHA256;
        sig.TimestampUrl = "http://timestamp.digicert.com";
        sig.SignatureImage = new PdfSignatureImage("IronPdf.png", 0, new Rectangle(150, 100, 200, 200));

        // Sign and save the PDF document
        sig.SignPdfFile("output.pdf");
    }
}
Imports IronPdf
Imports System.Security.Cryptography.X509Certificates

Public Class Program
	Shared Sub Main(ByVal args() As String)
		' Load the certificate with its password
		Dim sig = New PdfSignature("IronSoftware.pfx", "your-password")

		' Configure additional signature details
		sig.TimestampHashAlgorithm = TimestampHashAlgorithms.SHA256
		sig.TimestampUrl = "http://timestamp.digicert.com"
		sig.SignatureImage = New PdfSignatureImage("IronPdf.png", 0, New Rectangle(150, 100, 200, 200))

		' Sign and save the PDF document
		sig.SignPdfFile("output.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

Output

PDFsharp Sign PDF documents Digitally vs IronPDF (Code Example): Figure 3

This code demonstrates how to sign a PDF document using IronPDF's PdfSignature class. The program first creates a PdfSignature object, specifying the location of a .pfx certificate file and its password. It then sets additional signature properties, such as the hash algorithm (SHA256), timestamp URL, and a custom image for the signature (IronPdf.png).

Finally, the SignPdfFile method is called to apply the digital signature to the PDF document and save it as output.pdf. This process ensures the integrity and authenticity of the PDF by embedding the digital signature along with a timestamp and visual image.

PDFSharp:

  • Open-source under MIT License.
  • Requires external libraries (e.g., BouncyCastle) for advanced features like digital signing.

IronPDF:

Conclusion: IronPDF vs PDFsharp for Digital Signatures in C#

When comparing IronPDF and PDFsharp for adding digital signatures to PDFs in C#, both libraries offer distinct advantages depending on your project needs.

  • IronPDF is ideal for developers, whether they be independent freelance software developers, or developers working for a company, seeking a simple, easy-to-use API for applying digital signatures to PDFs, and comes with modern features. Its seamless integration with digital signature application, HTML-to-PDF conversion and other PDF functionalities makes it a great choice for commercial projects that prioritize ease of use and rapid implementation. With paid support and a clear commercial license structure, IronPDF is well-suited for businesses that require a straightforward, reliable solution.

  • PDFsharp excels in basic PDF creation and manipulation but lacks the advanced features and direct support for digital signatures that IronPDF offers. While PDFsharp is open-source and free to use, its API is less intuitive for working with digital signatures compared to IronPDF, and developers may need to employ additional solutions or third-party libraries to handle these features.

In summary, IronPDF is the best choice for developers looking for a simple, fast solution for digital signatures and related PDF tasks, especially in commercial environments. PDFsharp is more suited for basic PDF tasks but lacks the same ease of use and feature set for digital signatures, making it more suitable for simpler projects or those with additional customization needs.

Please notePDFsharp and BouncyCastle are registered trademarks of their respective owners. This site is not affiliated with, endorsed by, or sponsored by PDFsharp or BouncyCastle. 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 do digital signatures ensure the authenticity and integrity of PDF documents?

Digital signatures use cryptographic techniques to verify that a PDF document has not been altered after being signed. They confirm the identity of the signer and ensure that the document's content remains unchanged, providing security and legal validity.

What challenges might developers face when using PDFsharp for adding digital signatures?

When using PDFsharp to add digital signatures, developers typically need to integrate third-party libraries like BouncyCastle. This requirement can complicate the implementation process, as developers need to manage additional dependencies to create digital certificates and sign PDFs.

Why might a developer choose a commercial PDF library over an open-source one for digital signing?

A commercial PDF library offers advanced features, built-in support for digital signatures, and a user-friendly API. These attributes make it more suitable for developers seeking a rapid, reliable solution with dedicated support, especially in commercial projects where time and efficiency are crucial.

How can HTML be converted to PDF in a .NET application?

HTML can be converted to a PDF in a .NET application by using a library like IronPDF, which provides methods such as RenderHtmlAsPdf to directly transform HTML strings or files into PDF documents, supporting various styling and scripting options.

What are the benefits of using IronPDF for handling PDFs in commercial projects?

IronPDF offers a comprehensive suite of features for handling PDFs, including digital signatures, HTML-to-PDF conversion, and form processing. Its robust support and user-friendly API make it ideal for commercial projects that prioritize advanced functionality and rapid deployment.

Can you add a timestamp to a PDF digital signature using a .NET library?

Yes, with a library like IronPDF, you can add a timestamp to a PDF digital signature by specifying the timestamp server URL in the signature configuration. This feature enhances the trustworthiness and legal compliance of the signed document.

What should be considered when choosing a PDF library for digital signature implementation?

When choosing a PDF library for digital signatures, consider factors such as ease of use, support for advanced features, integration capabilities with third-party tools, and the availability of dedicated customer support, which are often more comprehensive in commercial libraries like IronPDF.

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