Digital Signatures in PDFs with C# and .NET

A digital signature is an important element in the process of ensuring the security and authenticity of documents. In this article, we will look at how you can add a digital signature to a PDF document using the library from SautinSoft PDF.Net in the C# and .NET development environment. Please note, that to woуrk with digital signatures, you will need a certificate in PFX format and a password for it. The example uses a test certificate, which must be replaced with your own certificate for real use.

Using digital signatures in PDF files using C# and .NET has several important goals and benefits:

  • Authentication. A digital signature confirms the authenticity of the document and certifies the identity of the signatory. This is especially important for legally significant documents, contracts and agreements.
  • Data integrity. A digital signature ensures that the document has not been modified after signing. Any changes to the document after signing will invalidate the signature.
  • Legal force. In many countries, digital signatures have the same legal force as handwritten signatures. This allows them to be used to sign contracts, agreements and other legally significant documents.
  • Safety. Digital signatures provide a high level of security, as they use cryptographic methods to protect data. This prevents forgery and unauthorized modification of documents.
  • Convenience and time saving. Digital signatures allow you to sign documents remotely, without the need for physical presence. This speeds up the process of signing and processing documents.
  • Saving resources. The use of digital signatures reduces the need for paper documents, which saves resources and reduces printing and storage costs.

The process of adding a digital signature consists of several steps:

  1. Add SautinSoft.PDF from NuGet.
  2. Load a PDF document.
  3. Add a signature field.
  4. Create and configure a new signer.
  5. Sign the PDF document.
  6. Save the document.

Input file:

Output result:

Полный код

using System;
using System.IO;
using SautinSoft;
using SautinSoft.Pdf;
using SautinSoft.Pdf.Annotations;
using SautinSoft.Pdf.Content;
using SautinSoft.Pdf.Forms;
using SautinSoft.Pdf.Security;

namespace Sample
{
    class Sample
    {
        /// <summary>
        /// Add sign in PDF
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/add-signature.php
        /// </remarks>
        static void Main(string[] args)
        {
            // Before starting this example, please get a free 100-day trial key:
            // https://sautinsoft.com/start-for-free/

            // Apply the key here:
            // PdfDocument.SetLicense("...");

            string pdfFile = Path.GetFullPath(@"..\..\..\simple text.pdf");

            var document = PdfDocument.Load(pdfFile);
            {
                // Add a signature field.
                var sig = document.Form.Fields.AddSignature(document.Pages[0], 10, 10, 250, 50);
                // Create new Signer.
                PdfSigner pdfSigner = new PdfSigner(@"..\..\..\sautinsoft.pfx", "123456789");
                // Configure signer.
                pdfSigner.Timestamper = new PdfTimestamper(@"https://tsa.cesnet.cz:5817/tsa");
                pdfSigner.SignatureFormat = PdfSignatureFormat.CAdES;
                pdfSigner.SignatureLevel = PdfSignatureLevel.PAdES_B_LTA;
                pdfSigner.HashAlgorithm = PdfHashAlgorithm.SHA256;
                pdfSigner.Location = "Test workplace";
                pdfSigner.Reason = "Test";
                var im = PdfImage.Load(@"..\..\..\JPEG2.jpg");
                sig.Appearance.Icon = im;
                sig.Appearance.TextPlacement = PdfTextPlacement.TextRightOfIcon;
                // Sign PDF Document.
                var si = sig.Sign(pdfSigner);
                // Save PDF Document.
                document.Save();
            }

            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(pdfFile) { UseShellExecute = true });
        }
    }
}

Download

Option Infer On

Imports System
Imports System.IO
Imports SautinSoft
Imports SautinSoft.Pdf
Imports SautinSoft.Pdf.Annotations
Imports SautinSoft.Pdf.Content
Imports SautinSoft.Pdf.Forms
Imports SautinSoft.Pdf.Security

Namespace Sample
	Friend Class Sample
		''' <summary>
		''' Add sign in PDF
		''' </summary>
		''' <remarks>
		''' Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/add-signature.php
		''' </remarks>
		Shared Sub Main(ByVal args() As String)
			' Before starting this example, please get a free 100-day trial key:
			' https://sautinsoft.com/start-for-free/

			' Apply the key here:
			' PdfDocument.SetLicense("...");

			Dim pdfFile As String = Path.GetFullPath("..\..\..\simple text.pdf")

			Dim document = PdfDocument.Load(pdfFile)
			If True Then
				' Add a signature field.
				Dim sig = document.Form.Fields.AddSignature(document.Pages(0), 10, 10, 250, 50)
				' Create new Signer.
				Dim pdfSigner As New PdfSigner("..\..\..\sautinsoft.pfx", "123456789")
				' Configure signer.
				pdfSigner.Timestamper = New PdfTimestamper("https://tsa.cesnet.cz:5817/tsa")
				pdfSigner.SignatureFormat = PdfSignatureFormat.CAdES
				pdfSigner.SignatureLevel = PdfSignatureLevel.PAdES_B_LTA
				pdfSigner.HashAlgorithm = PdfHashAlgorithm.SHA256
				pdfSigner.Location = "Test workplace"
				pdfSigner.Reason = "Test"
				Dim im = PdfImage.Load("..\..\..\JPEG2.jpg")
				sig.Appearance.Icon = im
				sig.Appearance.TextPlacement = PdfTextPlacement.TextRightOfIcon
				' Sign PDF Document.
				Dim si = sig.Sign(pdfSigner)
				' Save PDF Document.
				document.Save()
			End If

			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(pdfFile) With {.UseShellExecute = True})
		End Sub
	End Class
End Namespace

Download


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу support@sautinsoft.ru или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



Вопросы и предложения всегда приветствуются!

Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.