使用 C# 对 PDF 进行数字签名:开发者指南
本综合指南向 C# 开发人员展示了如何使用 IronPDF 对 PDF 进行数字签名,内容包括基于证书的签名、可视化图章和交互式表单字段,以确保文档的真实性和安全性。
在许多应用程序中,向 PDF 文档添加签名是一个常见的需求,但"签名"可能意味着不同的事情。 对于某些人来说,这涉及使用安全证书应用防篡改的数字签名。 对其他人来说,这可能是在文件上加盖可视的手写签名图像,或添加一个交互式表单字段供用户以电子方式签名。
本指南为 C# 开发人员提供了一个全面的操作指南,教您如何使用 IronPDF for .NET 库 完成所有这些任务。 我们将涵盖从应用安全的 X509Certificate2 数字签名到添加图形签名和创建交互式签名域的所有内容,确保您的 PDF 文档真实、安全且专业。
快速入门:使用IronPDF轻松对 PDF 进行数字签名
通过简单、直接的过程,快速开始使用 IronPDF 来数字签署您的 PDF 文档。 此示例演示如何使用 .pfx 证书验证和签署 PDF 文件,确保文档的完整性和真实性。 请按照以下步骤将数字签名无缝集成到您的应用程序中。
最小工作流程(5 个步骤)
- 安装 IronPDF library for .NET. 。
- Apply a digital signature using an `X509Certificate2` object.
- 添加可视图像来表示数字签名。
- 在 PDF 文件上加盖图形或手写签名。
- 添加交互式签名表单字段,用于电子签名。
如何使用证书对 PDF 应用数字签名?
您可以使用数字证书文件(例如 .pfx 或 .p12)对 PDF 文档应用数字签名,以保证文档的真实性和完整性。 此过程确保自签署以来文档未被更改。 如需全面了解数字签名功能,请浏览我们的综合数字签名指南。
IronPDF 为此目的提供了一个直接的 API,支持多种应用数字签名的方法。 此功能的核心是 PdfSignature 类,它封装了证书和签名的所有相关元数据。
| 签署方法 | 说明 |
|---|---|
| `签名` | 使用您创建和配置的 **`PdfSignature` 对象**签署 PDF。 |
| `SignWithFile` | 使用位于磁盘上的数字签名证书文件(`.pfx` 或 `.p12`)签署 PDF。 |
| `SignWithStore` | 使用来自计算机证书存储的数字签名签署 PDF,该数字签名由 **thumbprint ID** 标识。 |
使用 X509Certificate2 对象
为了实现最大程度的控制,您可以从证书文件创建 @@--CODE - 203--@@ 对象。IronPDF 完全符合 X509Certificate2 标准,为数字签名实现提供了一种强大而安全的方法。 创建证书对象时,请确保将 X509KeyStorageFlags 设置为 Exportable,因为底层加密 API 要求这样做。您可以在我们的代码库中查看数字签名的实际示例。
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")
上述代码首先生成一个简单的 PDF。 然后,它将 .pfx 证书文件加载到 X509Certificate2 对象中。 该对象代表数字身份,并传递给 PdfSignature 构造函数。 最后,pdf.Sign 方法在保存文档之前将此签名应用于文档。 For more information on the X509Certificate2 class, you can refer to the official Microsoft documentation.
在数字签名中添加细节
一个数字签名可以包含的不仅仅是证书; 您可以嵌入丰富的元数据以提供签名的上下文。 这包括签名位置、原因、联系信息和来自可信机构的安全时间戳。 您还可以设置和编辑元数据,以获得更多文档属性。
添加这些细节可以改进文档的审核轨迹,并为验证者提供有价值的信息。 IronPDF还支持使用现代哈希算法的时间戳服务器。
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.
// These properties enhance the signature's credibility and provide context
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.
// These properties enhance the signature's credibility and provide context
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.
Dim pdf = PdfDocument.FromFile("invoice.pdf")
' Create a PdfSignature object directly from the certificate file and password.
Dim signature = New PdfSignature("IronSoftware.pfx", "123456")
' Add detailed metadata to the signature for a comprehensive audit trail.
' These properties enhance the signature's credibility and provide context
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")
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")
如果签名证书不在系统的可信存储中,某些 PDF 查看器中可能会看到警告图标。 要获得绿色勾号,证书必须添加到查看器的可信身份中。
如何为数字签名添加视觉表示?
尽管数字签名是加密嵌入 PDF 中的,但通常在页面上有一个视觉表示是有用的。 这可以是公司徽标、手写签名图像或其他图形。 IronPDF可以轻松地将图像添加到 PdfSignature 对象中。
您可以从文件或流中加载图像,并将其精确定位在 PDF 的任何页面上。 支持的图像格式包括 PNG、JPEG、GIF、BMP、TIFF 和 WebP。这种技术类似于在 PDF 文档上给文本和图像盖章。
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).
// Rectangle parameters: x position, y position, width, height
var signatureRectangle = new Rectangle(350, 750, 200, 100);
// Option 1: Set the SignatureImage property directly.
// This is the most straightforward approach
signature.SignatureImage = new PdfSignatureImage("assets/visual-signature.png", 0, signatureRectangle);
// Option 2: Use the LoadSignatureImageFromFile method.
// This method provides the same functionality with a different syntax
signature.LoadSignatureImageFromFile("assets/visual-signature.png", 0, signatureRectangle);
// Option 3: Load an image from a stream. This is useful for images generated in memory.
// Perfect for scenarios where images are retrieved from databases or web services
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");
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).
// Rectangle parameters: x position, y position, width, height
var signatureRectangle = new Rectangle(350, 750, 200, 100);
// Option 1: Set the SignatureImage property directly.
// This is the most straightforward approach
signature.SignatureImage = new PdfSignatureImage("assets/visual-signature.png", 0, signatureRectangle);
// Option 2: Use the LoadSignatureImageFromFile method.
// This method provides the same functionality with a different syntax
signature.LoadSignatureImageFromFile("assets/visual-signature.png", 0, signatureRectangle);
// Option 3: Load an image from a stream. This is useful for images generated in memory.
// Perfect for scenarios where images are retrieved from databases or web services
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");
Imports IronPdf.Signing
Imports IronSoftware.Drawing
' This example demonstrates various ways to add a visual image to a PDF signature.
' Create a PdfSignature object.
Dim signature As New PdfSignature("IronSoftware.pfx", "123456")
' Define the position and size for the signature image on the first page (index 0).
' Rectangle parameters: x position, y position, width, height
Dim signatureRectangle As New Rectangle(350, 750, 200, 100)
' Option 1: Set the SignatureImage property directly.
' This is the most straightforward approach
signature.SignatureImage = New PdfSignatureImage("assets/visual-signature.png", 0, signatureRectangle)
' Option 2: Use the LoadSignatureImageFromFile method.
' This method provides the same functionality with a different syntax
signature.LoadSignatureImageFromFile("assets/visual-signature.png", 0, signatureRectangle)
' Option 3: Load an image from a stream. This is useful for images generated in memory.
' Perfect for scenarios where images are retrieved from databases or web services
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 As PdfDocument = PdfDocument.FromFile("invoice.pdf")
pdf.Sign(signature)
pdf.SaveAs("VisualSignature.pdf")
此代码展示了三种等效的方法来为数字签名添加视觉组件。 无论您是有一个磁盘上的图像还是在内存中的图像,都可以轻松地作为签名过程的一部分将它加盖到 PDF 上。 这弥合了不可见的加密安全性和可见的文档批准之间的差距。
签署后如何控制文档权限?
当您签署文档时,您可能想要指定在签署后可允许的更改。 例如,您可能希望完全锁定文档,或仅允许用户填写表单字段。 IronPDF允许您使用 SignaturePermissions 枚举设置这些权限。 有关更高级的权限控制,请参阅我们的设置 PDF 密码和权限指南。
设置签名权限是管理文档生命周期的关键部分。 它确保在应用签名后根据您的规则维护文档的完整性。 如果用户执行了不允许的操作,签名将失效。
| `SignaturePermissions`成员 | 定义 |
|---|---|
| `NoChangesAllowed` | 不得进行任何形式的修改。该文件已被锁定。 |
| `FormFillingAllowed` | 只允许填写现有表单字段和签名。 |
| `AnnotationsAndFormFillingAllowed` | 允许填写表格、签名、创建或修改注释。 |
保存特定的 PDF 修订版并签署
PDF 可以存储更改历史,就像版本控制系统一样。 这被称为增量保存。 当您签署 PDF 时,签名适用于文档的特定修订。 这对于文档经过多个审批阶段的工作流程至关重要。 请阅读我们的详细指南,了解更多关于管理PDF修订历史记录的信息。
在以下示例中,我们加载一个 PDF,进行编辑,然后签署当前修订版,同时仅允许在未来进行表单填充。 我们使用 SaveAsRevision 在保存文件之前将当前状态提交到文档的历史记录中。
using IronPdf.Signing;
// Load a PDF file with change tracking enabled.
// This enables incremental save functionality for revision management
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(...));
// Or: pdf.Form["fieldName"].Value = "New Value";
// 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.
// This creates a snapshot that can be referenced later
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.
// This enables incremental save functionality for revision management
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(...));
// Or: pdf.Form["fieldName"].Value = "New Value";
// 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.
// This creates a snapshot that can be referenced later
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.
' This enables incremental save functionality for revision management
Dim 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(...))
' Or: pdf.Form("fieldName").Value = "New Value"
' 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.
' This creates a snapshot that can be referenced later
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")
理解增量保存是高级 PDF 工作流程的关键。 虽然简单查看器可能只会显示最新版本,但像 Adobe Acrobat 这样的工具可以显示完整的修订历史,展示谁签署了哪个版本以及各签名间做了哪些更改。 IronPDF 使您可以完全以编程方式控制这一过程。
对于需要高安全性和合规性的复杂文档工作流程,企业可能需要一个全面的解决方案。 Iron Software 提供 Iron Suite,其中包括用于签署和操作的 IronPDF,以及用于广泛文档处理任务的其他库,仅需一次性购买费用。
如何管理和验证跨修订版的签名?
一个 PDF 文档可以在其各种修订版中应用多个签名。 IronPDF 提供工具来有效地管理这个历史。
-回滚到以前的版本:您可以使用 GetRevision 方法将文档还原到较早的状态。 这将丢弃该修订之后的所有更改和签名。
-验证所有签名:VerifySignatures 方法检查文档所有版本中所有签名的有效性。 只有当所有签名都有效且没有进行任何未经授权的更改时,才会返回 true。
-删除签名:RemoveSignatures 方法将从文档的每个版本中剥离所有数字签名,创建一个干净的、未签名的版本。
// Load a PDF with a complex signature history.
var pdf = PdfDocument.FromFile("multi_signed_report.pdf");
// Verify all signatures across all revisions.
// This ensures document integrity throughout its entire history
bool allSignaturesValid = pdf.VerifySignatures();
Console.WriteLine($"All signatures are valid: {allSignaturesValid}");
// Roll back to the first revision (index 0).
// Useful for reviewing the original document state
if (pdf.RevisionCount > 1)
{
PdfDocument firstRevision = pdf.GetRevision(0);
firstRevision.SaveAs("report_first_revision.pdf");
}
// Create a completely unsigned version of the document.
// This removes all digital signatures while preserving content
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.
// This ensures document integrity throughout its entire history
bool allSignaturesValid = pdf.VerifySignatures();
Console.WriteLine($"All signatures are valid: {allSignaturesValid}");
// Roll back to the first revision (index 0).
// Useful for reviewing the original document state
if (pdf.RevisionCount > 1)
{
PdfDocument firstRevision = pdf.GetRevision(0);
firstRevision.SaveAs("report_first_revision.pdf");
}
// Create a completely unsigned version of the document.
// This removes all digital signatures while preserving content
pdf.RemoveSignatures();
pdf.SaveAs("report_unsigned.pdf");
Imports System
' Load a PDF with a complex signature history.
Dim pdf = PdfDocument.FromFile("multi_signed_report.pdf")
' Verify all signatures across all revisions.
' This ensures document integrity throughout its entire history
Dim allSignaturesValid As Boolean = pdf.VerifySignatures()
Console.WriteLine($"All signatures are valid: {allSignaturesValid}")
' Roll back to the first revision (index 0).
' Useful for reviewing the original document state
If pdf.RevisionCount > 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.
' This removes all digital signatures while preserving content
pdf.RemoveSignatures()
pdf.SaveAs("report_unsigned.pdf")
如何在 PDF 上加盖手写签名?
有时,您不需要数字签名的加密安全性,而只是想应用一个视觉的、电子的签名,比如扫描的手写签名。 这通常被称为 stamping。 IronPDF可以使用其 Watermark 或 Stamp 功能来实现这一点。 如需了解更多高级水印选项,请浏览我们的自定义水印指南。
让我们从一个示例发票 PDF 和一个手写签名的图片开始。
在加盖签名之前的原始发票 PDF 。
这是我们将要应用的签名图像:
一个示例手写签名图像.
以下代码使用 Watermark 属性将此图像印在 PDF 的右下角。
using IronPdf.Editing;
// Load the existing PDF document.
var pdf = PdfDocument.FromFile("invoice.pdf");
// Create an HtmlStamp containing our signature image.
// HtmlStamp allows us to position HTML content precisely on the page
var signatureStamp = new HtmlStamp("<img src='assets/signature.png'/>")
{
// 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 for a more authentic look.
};
// Apply the stamp to all pages of the PDF.
// You can also specify specific page numbers if needed
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.
// HtmlStamp allows us to position HTML content precisely on the page
var signatureStamp = new HtmlStamp("<img src='assets/signature.png'/>")
{
// 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 for a more authentic look.
};
// Apply the stamp to all pages of the PDF.
// You can also specify specific page numbers if needed
pdf.ApplyStamp(signatureStamp);
// Save the modified PDF document.
pdf.SaveAs("official_invoice.pdf");
Imports IronPdf.Editing
' Load the existing PDF document.
Dim pdf = PdfDocument.FromFile("invoice.pdf")
' Create an HtmlStamp containing our signature image.
' HtmlStamp allows us to position HTML content precisely on the page
Dim signatureStamp = New HtmlStamp("<img src='assets/signature.png'/>") With {
' 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 for a more authentic look.
}
' Apply the stamp to all pages of the PDF.
' You can also specify specific page numbers if needed
pdf.ApplyStamp(signatureStamp)
' Save the modified PDF document.
pdf.SaveAs("official_invoice.pdf")
加盖印章后的 PDF 结果是什么样子的?
运行代码后,签名图像被加盖到文档上,创建了一个可视签名的发票。
最终带有右下角手写签名图像加盖的 PDF.
如何在 PDF 上添加交互式签名字段?
对于需要在像 Adobe Acrobat 这样的 PDF 查看器中由最终用户签署的文档,您可以添加一个交互式签名表单字段。 这就创建了一个空的、可点击的区域,提示用户应用他们自己的数字签名。 有关 PDF 表单的完整指南,请参阅我们的PDF 表单创建教程。
您可以创建一个 SignatureFormField 并将其添加到 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("<h1>Please Sign Below</h1>");
// Define the properties for the signature form field.
string fieldName = "ClientSignature"; // Unique identifier for the field
int pageIndex = 0; // Add to the first page (zero-indexed)
var fieldRect = new Rectangle(50, 200, 300, 100); // Position: (x, y), Size: (width, height)
// Create the SignatureFormField object.
// This creates an interactive field that users can click to sign
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("<h1>Please Sign Below</h1>");
// Define the properties for the signature form field.
string fieldName = "ClientSignature"; // Unique identifier for the field
int pageIndex = 0; // Add to the first page (zero-indexed)
var fieldRect = new Rectangle(50, 200, 300, 100); // Position: (x, y), Size: (width, height)
// Create the SignatureFormField object.
// This creates an interactive field that users can click to sign
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.
Dim renderer As New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Please Sign Below</h1>")
' Define the properties for the signature form field.
Dim fieldName As String = "ClientSignature" ' Unique identifier for the field
Dim pageIndex As Integer = 0 ' Add to the first page (zero-indexed)
Dim fieldRect As New Rectangle(50, 200, 300, 100) ' Position: (x, y), Size: (width, height)
' Create the SignatureFormField object.
' This creates an interactive field that users can click to sign
Dim signatureField As 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")
当用户打开这个 PDF 时,他们会看到一个可点击的字段,允许他们使用自己的数字 ID 完成签署过程。 您可以在我们的 如何创建 PDF 表单指南中了解有关创建和管理交互式表单的更多信息。
程序化添加到 PDF 文档的未签名、交互式签名字段.
如何从已验证的签名中检索签名人姓名?
要获取签署签名的证书所有者的通用名称,我们可以使用 VerifiedSignature 类来访问 SignerName 属性。 下面是一个代码片段,展示了如何完成此操作。
: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}");
});
Imports IronPdf
Imports System
' Import the Signed PDF report
Dim pdf = PdfDocument.FromFile("multi_signed_report.pdf")
' Using GetVerifiedSignatures() obtain a list of `VerifiedSignature` objects from the PDF
pdf.GetVerifiedSignatures().ForEach(Sub(signature)
' Print out the SignerName of each `VerifiedSignature` object
Console.WriteLine($"SignatureName: {signature.SignerName}")
End Sub)
导入签名的 PDF 文件后,我们利用 GetVerifiedSignatures 方法检索报告中的 VerifiedSignature 对象列表,并为每个签名打印 SignerName。
请注意,此值是从证书的主题可分辨名称 (SubjectDN) 中提取的,如果 CN 字段不存在,则将返回 null。
使用IronPDF进行 PDF 签名的下一步是什么?
本指南演示了 IronPDF 的强大和灵活的 PDF 签名功能。 无论您是需要应用带有详细元数据的安全数字签名、管理文档修订、加盖可视签名还是创建交互式表单,IronPDF 提供了一个全面且开发者友好的 API 来完成此任务。
要继续探索,您可以下载 IronPDF for .NET 库并获得 免费试用许可证 来在您的项目中测试其所有功能。 如需了解更高级的文档操作技巧,包括添加注释和使用表单字段,请查看我们丰富的文档和教程。
准备好看看您还能做些什么吗? 查看我们的教程页面:签名和保护PDFs
常见问题解答
如何使用 C# 中的证书对 PDF 进行数字签名?
有了 IronPDF,只需一行代码,您就可以使用 PdfSignature 类对 PDF 进行数字签名。只需用证书文件(.pfx 或 .p12)和密码创建一个新的 PdfSignature 对象,然后调用 SignPdfFile() 方法即可。例如:new IronPDF.Signing.PdfSignature("certificate.pfx", "password").SignPdfFile("input.pdf").这将使用你的 X509Certificate2 应用防篡改数字签名,以确保文档的真实性。
支持哪些类型的 PDF 签名?
IronPDF 支持三种主要的 PDF 签名类型:1)使用 X509Certificate2 证书进行身份验证和防篡改的数字签名;2)在文档中添加图形或手写签名图像的可视签名图章;3)允许用户对 PDF 进行电子签名的交互式签名表单字段。每种类型都能满足不同的文档安全和工作流程要求。
哪些证书格式可用于数字签名?
IronPDF 支持常见的数字证书格式,包括 .pfx(个人信息交换)和 .p12 文件。这些证书文件包含数字签名所需的公钥和私钥。IronPDF 中的 PdfSignature 类可以与任何 X509Certificate2 对象一起工作,从而为您加载和管理签名证书提供了灵活性。
我可以在数字签名中添加可视化表示吗?
是的,IronPDF 允许您在数字签名中添加可视化元素。您可以在加密签名旁添加图形表示,如手写签名图像、公司徽标或自定义印章。这将数字证书的安全性与可视化确认相结合,使签名文档既安全又具有专业性。
如何创建交互式签名字段供用户进行电子签名?
IronPDF 可让您在 PDF 文档中添加交互式签名表单字段。这些字段允许用户通过点击和绘制签名或上传签名图像来签署电子文档。该功能非常适合创建需要收集签名的文档,如需要多方签名的合同或表格。
签署 PDF 是否能确保文档的完整性?
是的,当您使用 IronPDF 使用 X509Certificate2 对 PDF 进行数字签名时,就会创建一个防篡改印章,确保文档的完整性。数字签名可保证文档在签署后未被篡改。签署后对 PDF 的任何修改都会导致签名无效,从而提醒接收者文档可能已被篡改。

