Cómo Firmar Archivos PDF en C# Usando IronPDF | Tutorial de IronPDF

A Developer's Guide to Digitally Signing PDFs with C#

This article was translated from English: Does it need improvement?
Translated
View the article in English

Adding a signature to a PDF document is a common requirement in many applications, but "signing" can mean different things. For some, it's about applying a tamper-proof digital signature using a security certificate. For others, it might be stamping a visual, handwritten signature image onto a document or adding an interactive form field for users to sign electronically.

This guide provides a comprehensive walkthrough for C# developers on how to accomplish all of these tasks using the IronPDF for .NET library. We will cover everything from applying a secure X509Certificate2 digital signature to stamping graphical signatures and creating interactive signature fields, ensuring your PDF documents are authentic, secure, and professional.

Quickstart: Effortlessly Digitally Sign a PDF Using IronPDF

Get started quickly with IronPDF to digitally sign your PDF documents using a simple, straightforward process. This example demonstrates how to use a .pfx certificate to authenticate and sign a PDF file, ensuring document integrity and authenticity. Follow these steps to seamlessly integrate digital signing into your application, empowering your users with secure and reliable PDF functionalities.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronPDF with NuGet Package Manager

    PM > Install-Package IronPdf

  2. Copy and run this code snippet.

    new IronPdf.Signing.PdfSignature("certificate.pfx", "password").SignPdfFile("input.pdf");
  3. Deploy to test on your live environment

    Start using IronPDF in your project today with a free trial
    arrow pointer

How Do I Apply a Digital Signature to a PDF with a Certificate?

You can apply a digital signature to a PDF document using a digital certificate file (such as .pfx or .p12) to guarantee the document's authenticity and integrity. This process ensures that the document has not been altered since it was signed.

IronPDF provides a straightforward API for this purpose, supporting multiple ways to apply a digital signature. The core of this functionality revolves around the PdfSignature class, which encapsulates the certificate and all associated metadata for the signature.

Signing Method Description
Sign Signs a PDF with a PdfSignature object that you create and configure.
SignWithFile Signs a PDF using a digital signature certificate file (.pfx or .p12) located on disk.
SignWithStore Signs a PDF with a digital signature from your computer's certificate store, identified by its thumbprint ID.

Using an X509Certificate2 Object

For maximum control, you can create an X509Certificate2 object from your certificate file. IronPDF fully complies with the X509Certificate2 standard, providing a robust and secure method for digital signature implementation. When creating the certificate object, ensure the X509KeyStorageFlags are set to Exportable, as this is required by the underlying cryptographic APIs.

Install-Package IronPdf
using IronPdf;
using IronPdf.Signing;
using System.Security.Cryptography.X509Certificates;

// Create a new PDF from an HTML string for demonstration.
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Signed Document</h1><p>This document has been digitally signed.</p>");

// Load the certificate from a .pfx file with its password.
// The X509KeyStorageFlags.Exportable flag is crucial for allowing the private key to be used in the signing process.
var cert = new X509Certificate2("IronSoftware.pfx", "123456", X509KeyStorageFlags.Exportable);

// Create a PdfSignature object using the loaded certificate.
var signature = new PdfSignature(cert);

// Apply the signature to the PDF document.
pdf.Sign(signature);

// Save the securely signed PDF document.
pdf.SaveAs("Signed.pdf");
using IronPdf;
using IronPdf.Signing;
using System.Security.Cryptography.X509Certificates;

// Create a new PDF from an HTML string for demonstration.
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Signed Document</h1><p>This document has been digitally signed.</p>");

// Load the certificate from a .pfx file with its password.
// The X509KeyStorageFlags.Exportable flag is crucial for allowing the private key to be used in the signing process.
var cert = new X509Certificate2("IronSoftware.pfx", "123456", X509KeyStorageFlags.Exportable);

// Create a PdfSignature object using the loaded certificate.
var signature = new PdfSignature(cert);

// Apply the signature to the PDF document.
pdf.Sign(signature);

// Save the securely signed PDF document.
pdf.SaveAs("Signed.pdf");
Imports IronPdf
Imports IronPdf.Signing
Imports System.Security.Cryptography.X509Certificates

' Create a new PDF from an HTML string for demonstration.
Private renderer = New ChromePdfRenderer()
Private pdf = renderer.RenderHtmlAsPdf("<h1>Signed Document</h1><p>This document has been digitally signed.</p>")

' Load the certificate from a .pfx file with its password.
' The X509KeyStorageFlags.Exportable flag is crucial for allowing the private key to be used in the signing process.
Private cert = New X509Certificate2("IronSoftware.pfx", "123456", X509KeyStorageFlags.Exportable)

' Create a PdfSignature object using the loaded certificate.
Private signature = New PdfSignature(cert)

' Apply the signature to the PDF document.
pdf.Sign(signature)

' Save the securely signed PDF document.
pdf.SaveAs("Signed.pdf")
$vbLabelText   $csharpLabel

The code above first generates a simple PDF. It then loads a .pfx certificate file into an X509Certificate2 object. This object, which represents the digital identity, is passed to the PdfSignature constructor. Finally, the pdf.Sign method applies this signature to the document before saving it. For more information on the X509Certificate2 class, you can refer to the official Microsoft documentation.

Adding Granular Details to a Digital Signature

A digital signature can contain more than just the certificate; you can embed rich metadata to provide context about the signature. This includes the signing location, reason, contact information, and a secure timestamp from a trusted authority.

Adding these details improves the document's audit trail and provides verifiers with valuable information. IronPDF also supports timestamping servers that use modern SHA256 and SHA512 hash algorithms.

using IronPdf;
using IronPdf.Signing;
using IronSoftware.Drawing;
using System;

// Load an existing PDF document to be signed.
var pdf = PdfDocument.FromFile("invoice.pdf");

// Create a PdfSignature object directly from the certificate file and password.
var signature = new PdfSignature("IronSoftware.pfx", "123456");

// Add detailed metadata to the signature for a comprehensive audit trail.
signature.SignatureDate = DateTime.Now;
signature.SigningContact = "legal@ironsoftware.com";
signature.SigningLocation = "Chicago, USA";
signature.SigningReason = "Contractual Agreement";

// Add a secure timestamp from a trusted Time Stamp Authority (TSA).
// This provides cryptographic proof of the signing time.
signature.TimeStampUrl = new Uri("[http://timestamp.digicert.com](http://timestamp.digicert.com)");
signature.TimestampHashAlgorithm = TimestampHashAlgorithms.SHA256;

// Apply a visual appearance to the signature. (More on this in the next section)
signature.SignatureImage = new PdfSignatureImage("assets/visual-signature.png", 0, new Rectangle(350, 750, 200, 100));

// Sign the PDF document with the configured signature object.
pdf.Sign(signature);

// Save the final, signed PDF document.
pdf.SaveAs("DetailedSignature.pdf");
using IronPdf;
using IronPdf.Signing;
using IronSoftware.Drawing;
using System;

// Load an existing PDF document to be signed.
var pdf = PdfDocument.FromFile("invoice.pdf");

// Create a PdfSignature object directly from the certificate file and password.
var signature = new PdfSignature("IronSoftware.pfx", "123456");

// Add detailed metadata to the signature for a comprehensive audit trail.
signature.SignatureDate = DateTime.Now;
signature.SigningContact = "legal@ironsoftware.com";
signature.SigningLocation = "Chicago, USA";
signature.SigningReason = "Contractual Agreement";

// Add a secure timestamp from a trusted Time Stamp Authority (TSA).
// This provides cryptographic proof of the signing time.
signature.TimeStampUrl = new Uri("[http://timestamp.digicert.com](http://timestamp.digicert.com)");
signature.TimestampHashAlgorithm = TimestampHashAlgorithms.SHA256;

// Apply a visual appearance to the signature. (More on this in the next section)
signature.SignatureImage = new PdfSignatureImage("assets/visual-signature.png", 0, new Rectangle(350, 750, 200, 100));

// Sign the PDF document with the configured signature object.
pdf.Sign(signature);

// Save the final, signed PDF document.
pdf.SaveAs("DetailedSignature.pdf");
Imports IronPdf
Imports IronPdf.Signing
Imports IronSoftware.Drawing
Imports System

' Load an existing PDF document to be signed.
Private pdf = PdfDocument.FromFile("invoice.pdf")

' Create a PdfSignature object directly from the certificate file and password.
Private signature = New PdfSignature("IronSoftware.pfx", "123456")

' Add detailed metadata to the signature for a comprehensive audit trail.
signature.SignatureDate = DateTime.Now
signature.SigningContact = "legal@ironsoftware.com"
signature.SigningLocation = "Chicago, USA"
signature.SigningReason = "Contractual Agreement"

' Add a secure timestamp from a trusted Time Stamp Authority (TSA).
' This provides cryptographic proof of the signing time.
signature.TimeStampUrl = New Uri("[http://timestamp.digicert.com](http://timestamp.digicert.com)")
signature.TimestampHashAlgorithm = TimestampHashAlgorithms.SHA256

' Apply a visual appearance to the signature. (More on this in the next section)
signature.SignatureImage = New PdfSignatureImage("assets/visual-signature.png", 0, New Rectangle(350, 750, 200, 100))

' Sign the PDF document with the configured signature object.
pdf.Sign(signature)

' Save the final, signed PDF document.
pdf.SaveAs("DetailedSignature.pdf")
$vbLabelText   $csharpLabel

You may notice a warning icon in some PDF viewers if the signing certificate is not in the system's trusted store. To get a green checkmark, the certificate must be added to the viewer's trusted identities.

How Can I Add a Visual Representation to a Digital Signature?

While a digital signature is cryptographically embedded in the PDF, it's often useful to have a visual representation on the page. This can be a company logo, a handwritten signature image, or other graphics. IronPDF makes it easy to add an image to a PdfSignature object.

You can load an image from a file or a stream and position it precisely on any page of the PDF. Supported image formats include PNG, JPEG, GIF, BMP, TIFF, and WebP.

using IronPdf.Signing;
using IronSoftware.Drawing;

// This example demonstrates various ways to add a visual image to a PDF signature.

// Create a PdfSignature object.
var signature = new PdfSignature("IronSoftware.pfx", "123456");

// Define the position and size for the signature image on the first page (index 0).
var signatureRectangle = new Rectangle(350, 750, 200, 100);

// Option 1: Set the SignatureImage property directly.
signature.SignatureImage = new PdfSignatureImage("assets/visual-signature.png", 0, signatureRectangle);

// Option 2: Use the LoadSignatureImageFromFile method.
signature.LoadSignatureImageFromFile("assets/visual-signature.png", 0, signatureRectangle);

// Option 3: Load an image from a stream. This is useful for images generated in memory.
AnyBitmap image = AnyBitmap.FromFile("assets/visual-signature.png");
using (var imageStream = image.ToStream())
{
    signature.LoadSignatureImageFromStream(imageStream, 0, signatureRectangle);
}

// After configuring the signature image, apply it to a PDF.
var pdf = PdfDocument.FromFile("invoice.pdf");
pdf.Sign(signature);
pdf.SaveAs("VisualSignature.pdf");
</span><br class="ProseMirror-trailingBreak">
using IronPdf.Signing;
using IronSoftware.Drawing;

// This example demonstrates various ways to add a visual image to a PDF signature.

// Create a PdfSignature object.
var signature = new PdfSignature("IronSoftware.pfx", "123456");

// Define the position and size for the signature image on the first page (index 0).
var signatureRectangle = new Rectangle(350, 750, 200, 100);

// Option 1: Set the SignatureImage property directly.
signature.SignatureImage = new PdfSignatureImage("assets/visual-signature.png", 0, signatureRectangle);

// Option 2: Use the LoadSignatureImageFromFile method.
signature.LoadSignatureImageFromFile("assets/visual-signature.png", 0, signatureRectangle);

// Option 3: Load an image from a stream. This is useful for images generated in memory.
AnyBitmap image = AnyBitmap.FromFile("assets/visual-signature.png");
using (var imageStream = image.ToStream())
{
    signature.LoadSignatureImageFromStream(imageStream, 0, signatureRectangle);
}

// After configuring the signature image, apply it to a PDF.
var pdf = PdfDocument.FromFile("invoice.pdf");
pdf.Sign(signature);
pdf.SaveAs("VisualSignature.pdf");
</span><br class="ProseMirror-trailingBreak">
Imports IronPdf.Signing
Imports IronSoftware.Drawing

' This example demonstrates various ways to add a visual image to a PDF signature.

' Create a PdfSignature object.
Private signature = New PdfSignature("IronSoftware.pfx", "123456")

' Define the position and size for the signature image on the first page (index 0).
Private signatureRectangle = New Rectangle(350, 750, 200, 100)

' Option 1: Set the SignatureImage property directly.
signature.SignatureImage = New PdfSignatureImage("assets/visual-signature.png", 0, signatureRectangle)

' Option 2: Use the LoadSignatureImageFromFile method.
signature.LoadSignatureImageFromFile("assets/visual-signature.png", 0, signatureRectangle)

' Option 3: Load an image from a stream. This is useful for images generated in memory.
Dim image As AnyBitmap = AnyBitmap.FromFile("assets/visual-signature.png")
Using imageStream = image.ToStream()
	signature.LoadSignatureImageFromStream(imageStream, 0, signatureRectangle)
End Using

' After configuring the signature image, apply it to a PDF.
Dim pdf = PdfDocument.FromFile("invoice.pdf")
pdf.Sign(signature)
pdf.SaveAs("VisualSignature.pdf")
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'</span><br class="ProseMirror-trailingBreak">
$vbLabelText   $csharpLabel

This code showcases three equivalent ways to add a visual component to a digital signature. Whether you have an image on disk or in memory, you can easily stamp it onto the PDF as part of the signing process. This bridges the gap between invisible cryptographic security and visible document approval.

How Can I Control Document Permissions After Signing?

When you sign a document, you might want to specify what changes, if any, are permitted afterward. For example, you might want to lock the document completely or only allow users to fill in form fields. IronPDF lets you set these permissions using the SignaturePermissions enumeration.

Setting signature permissions is a key part of managing a document's lifecycle. It ensures that the document's integrity is maintained according to your rules after your signature is applied. If a user performs a disallowed action, the signature will be invalidated.

SignaturePermissions Member Definition
NoChangesAllowed No changes of any kind are permitted. The document is effectively locked.
FormFillingAllowed Only filling in existing form fields and signing is allowed.
AnnotationsAndFormFillingAllowed Allows form filling, signing, and creating or modifying annotations.

Saving and Signing a Specific PDF Revision

PDFs can store a history of changes, much like a version control system. This is known as incremental saving. When you sign a PDF, the signature applies to a specific revision of the document. This is crucial for workflows where a document goes through multiple stages of approval.

In the following example, we load a PDF, make edits, and then sign the current revision while allowing only form-filling as a future change. We use SaveAsRevision to commit the current state to the document's history before saving the file.

using IronPdf.Signing;

// Load a PDF file with change tracking enabled.
var pdf = PdfDocument.FromFile("annual_census.pdf", ChangeTrackingModes.EnableChangeTracking);

// Placeholder for edits: You might add text, fill forms, or add annotations here.
// For example: pdf.Annotations.Add(new TextAnnotation(...));

// Sign the current state of the document using SignWithFile for convenience.
// We set permissions to allow further signatures and form filling.
pdf.SignWithFile(
    "assets/IronSignature.p12", 
    "password", 
    SignaturePermissions.AdditionalSignaturesAndFormFillingAllowed);

// Save the current state as a distinct revision within the PDF's history.
PdfDocument pdfWithRevision = pdf.SaveAsRevision();

// Save the final PDF with its full revision history to a new file.
pdfWithRevision.SaveAs("annual_census_signed.pdf");
using IronPdf.Signing;

// Load a PDF file with change tracking enabled.
var pdf = PdfDocument.FromFile("annual_census.pdf", ChangeTrackingModes.EnableChangeTracking);

// Placeholder for edits: You might add text, fill forms, or add annotations here.
// For example: pdf.Annotations.Add(new TextAnnotation(...));

// Sign the current state of the document using SignWithFile for convenience.
// We set permissions to allow further signatures and form filling.
pdf.SignWithFile(
    "assets/IronSignature.p12", 
    "password", 
    SignaturePermissions.AdditionalSignaturesAndFormFillingAllowed);

// Save the current state as a distinct revision within the PDF's history.
PdfDocument pdfWithRevision = pdf.SaveAsRevision();

// Save the final PDF with its full revision history to a new file.
pdfWithRevision.SaveAs("annual_census_signed.pdf");
Imports IronPdf.Signing

' Load a PDF file with change tracking enabled.
Private pdf = PdfDocument.FromFile("annual_census.pdf", ChangeTrackingModes.EnableChangeTracking)

' Placeholder for edits: You might add text, fill forms, or add annotations here.
' For example: pdf.Annotations.Add(new TextAnnotation(...));

' Sign the current state of the document using SignWithFile for convenience.
' We set permissions to allow further signatures and form filling.
pdf.SignWithFile("assets/IronSignature.p12", "password", SignaturePermissions.AdditionalSignaturesAndFormFillingAllowed)

' Save the current state as a distinct revision within the PDF's history.
Dim pdfWithRevision As PdfDocument = pdf.SaveAsRevision()

' Save the final PDF with its full revision history to a new file.
pdfWithRevision.SaveAs("annual_census_signed.pdf")
$vbLabelText   $csharpLabel

Understanding incremental saves is key to advanced PDF workflows. While a simple viewer might only show the latest version, a tool like Adobe Acrobat can reveal the entire revision history, showing who signed which version and what changes were made between signatures. IronPDF gives you full programmatic control over this process.

For businesses managing complex document workflows that require high security and compliance, a comprehensive solution may be needed. Iron Software offers Iron Suite, which includes IronPDF for signing and manipulation, plus other libraries for a wide range of document processing tasks, available for a single one-time payment.

How Can I Manage and Verify Signatures Across Revisions?

A PDF document can have multiple signatures applied across its various revisions. IronPDF provides tools to manage this history effectively.

  • Roll Back to a Previous Revision: You can revert a document to an earlier state using the GetRevision method. This will discard all changes and signatures made after that revision.
  • Verify All Signatures: The VerifySignatures method checks the validity of all signatures across all revisions of the document. It returns true only if every signature is valid and no unauthorized changes have been made.
  • Remove Signatures: The RemoveSignatures method will strip all digital signatures from every revision of the document, creating a clean, unsigned version.
// Load a PDF with a complex signature history.
var pdf = PdfDocument.FromFile("multi_signed_report.pdf");

// Verify all signatures across all revisions.
bool allSignaturesValid = pdf.VerifySignatures();
Console.WriteLine($"All signatures are valid: {allSignaturesValid}");

// Roll back to the first revision (index 0).
if (pdf.RevisionCount &gt; 1)
{
    PdfDocument firstRevision = pdf.GetRevision(0);
    firstRevision.SaveAs("report_first_revision.pdf");
}

// Create a completely unsigned version of the document.
pdf.RemoveSignatures();
pdf.SaveAs("report_unsigned.pdf");
// Load a PDF with a complex signature history.
var pdf = PdfDocument.FromFile("multi_signed_report.pdf");

// Verify all signatures across all revisions.
bool allSignaturesValid = pdf.VerifySignatures();
Console.WriteLine($"All signatures are valid: {allSignaturesValid}");

// Roll back to the first revision (index 0).
if (pdf.RevisionCount &gt; 1)
{
    PdfDocument firstRevision = pdf.GetRevision(0);
    firstRevision.SaveAs("report_first_revision.pdf");
}

// Create a completely unsigned version of the document.
pdf.RemoveSignatures();
pdf.SaveAs("report_unsigned.pdf");
' Load a PDF with a complex signature history.
Dim pdf = PdfDocument.FromFile("multi_signed_report.pdf")

' Verify all signatures across all revisions.
Dim allSignaturesValid As Boolean = pdf.VerifySignatures()
Console.WriteLine($"All signatures are valid: {allSignaturesValid}")

' Roll back to the first revision (index 0).
If pdf.RevisionCount And gt; 1 Then
	Dim firstRevision As PdfDocument = pdf.GetRevision(0)
	firstRevision.SaveAs("report_first_revision.pdf")
End If

' Create a completely unsigned version of the document.
pdf.RemoveSignatures()
pdf.SaveAs("report_unsigned.pdf")
$vbLabelText   $csharpLabel

How Do I Stamp a Handwritten Signature onto a PDF?

Sometimes, you don't need the cryptographic security of a digital signature but simply want to apply a visual, electronic signature, like a scanned handwritten signature. This is often referred to as stamping. IronPDF can do this using its Watermark or Stamp features.

Let's start with a sample invoice PDF and a .png image of a handwritten signature.

The original invoice PDF before stamping a signature.

Here is the signature image we will apply:

An image of an handwritten signature A sample handwritten signature image.

The following code uses the Watermark property to stamp this image onto the bottom-right corner of the PDF.

using IronPdf.Editing;

// Load the existing PDF document.
var pdf = PdfDocument.FromFile("invoice.pdf");

// Create an HtmlStamp containing our signature image.
var signatureStamp = new HtmlStamp("&lt;img src='assets/signature.png'/&gt;")
{
    // Configure the stamp's position and appearance.
    VerticalAlignment = VerticalAlignment.Bottom,
    HorizontalAlignment = HorizontalAlignment.Right,
    Margin = 10, // Add some space from the edge.
    Opacity = 90 // Make it slightly transparent.
};

// Apply the stamp to all pages of the PDF.
pdf.ApplyStamp(signatureStamp);

// Save the modified PDF document.
pdf.SaveAs("official_invoice.pdf");
using IronPdf.Editing;

// Load the existing PDF document.
var pdf = PdfDocument.FromFile("invoice.pdf");

// Create an HtmlStamp containing our signature image.
var signatureStamp = new HtmlStamp("&lt;img src='assets/signature.png'/&gt;")
{
    // Configure the stamp's position and appearance.
    VerticalAlignment = VerticalAlignment.Bottom,
    HorizontalAlignment = HorizontalAlignment.Right,
    Margin = 10, // Add some space from the edge.
    Opacity = 90 // Make it slightly transparent.
};

// Apply the stamp to all pages of the PDF.
pdf.ApplyStamp(signatureStamp);

// Save the modified PDF document.
pdf.SaveAs("official_invoice.pdf");
Imports IronPdf.Editing

' Load the existing PDF document.
Private pdf = PdfDocument.FromFile("invoice.pdf")

' Create an HtmlStamp containing our signature image.
Dim signatureStamp = New HtmlStamp("&lt;img src='assets/signature.png'/&gt;")
If True Then
	' Configure the stamp's position and appearance.
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: VerticalAlignment = VerticalAlignment.Bottom, HorizontalAlignment = HorizontalAlignment.Right, Margin = 10, Opacity = 90
	10, Opacity = 90 ' Make it slightly transparent.
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: VerticalAlignment = VerticalAlignment.Bottom, HorizontalAlignment = HorizontalAlignment.Right, Margin = 10, Opacity
	HorizontalAlignment.Right, Margin = 10, Opacity
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: VerticalAlignment = VerticalAlignment.Bottom, HorizontalAlignment = HorizontalAlignment.Right, Margin
	VerticalAlignment.Bottom, HorizontalAlignment = HorizontalAlignment.Right, Margin
	VerticalAlignment = VerticalAlignment.Bottom, HorizontalAlignment
End If

' Apply the stamp to all pages of the PDF.
pdf.ApplyStamp(signatureStamp)

' Save the modified PDF document.
pdf.SaveAs("official_invoice.pdf")
$vbLabelText   $csharpLabel

Stamped PDF Result

After running the code, the signature image is stamped onto the document, creating a visually signed invoice.

The final PDF with the handwritten signature image stamped in the bottom-right corner.

How Can I Add an Interactive Signature Field to a PDF?

For documents that need to be signed by an end-user in a PDF viewer like Adobe Acrobat, you can add an interactive signature form field. This creates an empty, clickable area that prompts the user to apply their own digital signature.

You can create a SignatureFormField and add it to the PDF's form collection. You have precise control over its location and size on the page.

using IronPdf.Forms;
using IronSoftware.Drawing;

// Create a new PDF to add the signature field to.
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("&lt;h1&gt;Please Sign Below&lt;/h1&gt;");

// Define the properties for the signature form field.
string fieldName = "ClientSignature";
int pageIndex = 0; // Add to the first page.
var fieldRect = new Rectangle(50, 200, 300, 100); // Position: (x, y), Size: (width, height)

// Create the SignatureFormField object.
var signatureField = new SignatureFormField(fieldName, pageIndex, fieldRect);

// Add the signature field to the PDF's form.
pdf.Form.Add(signatureField);

// Save the PDF with the new interactive signature field.
pdf.SaveAs("interactive_signature.pdf");
using IronPdf.Forms;
using IronSoftware.Drawing;

// Create a new PDF to add the signature field to.
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("&lt;h1&gt;Please Sign Below&lt;/h1&gt;");

// Define the properties for the signature form field.
string fieldName = "ClientSignature";
int pageIndex = 0; // Add to the first page.
var fieldRect = new Rectangle(50, 200, 300, 100); // Position: (x, y), Size: (width, height)

// Create the SignatureFormField object.
var signatureField = new SignatureFormField(fieldName, pageIndex, fieldRect);

// Add the signature field to the PDF's form.
pdf.Form.Add(signatureField);

// Save the PDF with the new interactive signature field.
pdf.SaveAs("interactive_signature.pdf");
Imports IronPdf.Forms
Imports IronSoftware.Drawing

' Create a new PDF to add the signature field to.
Private renderer = New ChromePdfRenderer()
Private pdf = renderer.RenderHtmlAsPdf("&lt;h1&gt;Please Sign Below&lt;/h1&gt;")

' Define the properties for the signature form field.
Private fieldName As String = "ClientSignature"
Private pageIndex As Integer = 0 ' Add to the first page.
Private fieldRect = New Rectangle(50, 200, 300, 100) ' Position: (x, y), Size: (width, height)

' Create the SignatureFormField object.
Private signatureField = New SignatureFormField(fieldName, pageIndex, fieldRect)

' Add the signature field to the PDF's form.
pdf.Form.Add(signatureField)

' Save the PDF with the new interactive signature field.
pdf.SaveAs("interactive_signature.pdf")
$vbLabelText   $csharpLabel

When a user opens this PDF, they will see a clickable field, allowing them to complete the signing process using their own digital ID. You can learn more about creating and managing interactive forms in our How-To guide on creating PDF forms.

Unsigned signature An unsigned, interactive signature field added programmatically to a PDF document.

Retrieving the Signer Name from Verified Signatures

To obtain the common name of the certificate owner who signed a signature, we can use the VerifiedSignature class to access the SignerName property. Below is a code snippet demonstrating how to accomplish this.

:path=/static-assets/pdf/content-code-examples/how-to/signing-find-signer-name.cs
using IronPdf;
using System;

// Import the Signed PDF report
var pdf = PdfDocument.FromFile("multi_signed_report.pdf");

// Using GetVerifiedSignatures() obtain a list of `VerifiedSignature` objects from the PDF
pdf.GetVerifiedSignatures().ForEach(signature =>
{
    // Print out the SignerName of each `VerifiedSignature` object
    Console.WriteLine($"SignatureName: {signature.SignerName}");
});
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

After importing the signed PDF file, we utilize the GetVerifiedSignatures method to retrieve a list of VerifiedSignature objects within the report and print the SignerName for each signature.

Por favor notaPlease note that this value is extracted from the certificate's Subject Distinguished Name (SubjectDN) and will return null if the CN field is not present.

Next Steps

This guide has demonstrated the powerful and flexible PDF signing capabilities of IronPDF. Whether you need to apply secure digital signatures with detailed metadata, manage document revisions, stamp visual signatures, or create interactive forms, IronPDF provides a comprehensive and developer-friendly API to get the job done.

To continue exploring, you can download the IronPDF library for .NET and get a free trial license to test out all its features in your projects.

Ready to see what else you can do? Check out our tutorial page here: Sign and Secure PDFs

Preguntas Frecuentes

¿Cómo puedo aplicar una firma digital a un PDF usando un archivo de certificado en C#?

Para aplicar una firma digital a un PDF usando un archivo de certificado en C#, puedes utilizar IronPDF. Carga tu certificado en un objeto X509Certificate2 y usa la clase PdfSignature de IronPDF para aplicarlo a tu documento con el método Sign.

¿Cuáles son los beneficios de usar una firma digital para documentos PDF?

Las firmas digitales proporcionan autenticación e integridad para documentos PDF. Al usar IronPDF, puedes asegurar que tu documento está firmado por una fuente verificada y que no ha sido alterado desde que se aplicó la firma.

¿Cómo puedo agregar una firma manuscrita a un PDF en C#?

IronPDF te permite agregar una firma manuscrita estampando una imagen de tu firma en el PDF. Puedes usar el método ApplyStamp con un HtmlStamp, especificando el archivo de imagen, para lograr esto.

¿Cuál es el proceso para agregar un campo de firma interactivo a un PDF?

Para agregar un campo de firma interactivo a un PDF, crea un objeto SignatureFormField con el nombre, la página y la ubicación deseados. Agrega este campo a la colección PdfDocument.Form usando IronPDF antes de guardar el documento.

¿Puedo controlar los permisos en un PDF firmado?

Sí, al firmar un PDF con IronPDF, puedes especificar SignaturePermissions para controlar qué cambios están permitidos después de que el documento esté firmado. Las opciones incluyen NoChangesAllowed, FormFillingAllowed, y AnnotationsAndFormFillingAllowed.

¿Cómo verifico la autenticidad de la firma digital de un PDF?

IronPDF proporciona un método VerifySignatures que verifica la validez de todas las firmas en un PDF. Devuelve un booleano que indica si todas las firmas son auténticas y no han sido manipuladas.

¿Qué es el guardado incremental en PDFs y por qué es útil?

El guardado incremental en PDFs permite almacenar múltiples versiones de documentos en un solo archivo. Esta característica es útil para mantener un historial de cambios y asegurar que cada firma digital corresponda a la versión correcta del documento en el momento de la firma.

¿Cómo puedo agregar metadatos a una firma digital en un PDF?

Usando IronPDF, puedes enriquecer las firmas digitales con metadatos como el motivo de la firma, la ubicación y el sello de tiempo. Esto se puede establecer al crear un objeto PdfSignature, permitiendo una documentación detallada del proceso de firma.

¿Puedo usar las funciones de firma digital de IronPDF en aplicaciones .NET 10?

Sí. IronPDF es totalmente compatible con .NET 10, por lo que el mismo flujo de trabajo de firma digital basado en X509Certificate2 que se muestra en este artículo funciona en aplicaciones console, web y de servicio de .NET 10. Simplemente cree un proyecto .NET 10, instale el paquete más reciente de IronPdf desde NuGet y reutilice el código de firma para aplicar firmas invisibles o visibles, imágenes de firma y campos de formulario de firma.

Jacob Mellor, Director de Tecnología @ Team Iron
Director de Tecnología

Jacob Mellor es Director de Tecnología en Iron Software y un ingeniero visionario que lidera la tecnología PDF en C#. Como el desarrollador original detrás de la base de código central de Iron Software, ha moldeado la arquitectura de productos de la compañía desde ...

Leer más
Revisado por
Jeff Fritz
Jeffrey T. Fritz
Gerente Principal de Programas - Equipo de la Comunidad .NET
Jeff también es Gerente Principal de Programas para los equipos de .NET y Visual Studio. Es el productor ejecutivo de la serie de conferencias virtuales .NET Conf y anfitrión de 'Fritz and Friends', una transmisión en vivo para desarrolladores que se emite dos veces a la semana donde habla sobre tecnología y escribe código junto con la audiencia. Jeff escribe talleres, presentaciones, y planifica contenido para los eventos de desarrolladores más importantes de Microsoft, incluyendo Microsoft Build, Microsoft Ignite, .NET Conf y la Cumbre de Microsoft MVP.
¿Listo para empezar?
Nuget Descargas 16,154,058 | Versión: 2025.11 recién lanzado