使用 C# 对 PDF 进行数字签名的开发人员指南
本指南介绍如何使用 IronPDF 在 C# 中对 PDF 进行数字签名,并介绍基于证书的数字签名、可见签名和交互式签名字段。
PDF 签名有几种不同的形式。数字签名使用安全证书,让签名后的更改可被检测。可见签名是在页面上加盖手写签名图像。交互式签名字段提供一个空白区域,接收者可用自己的数字 ID 签名。IronPDF for .NET 库支持这三种形式。本指南从使用 X509Certificate2 进行数字签名讲起,最后介绍签名字段和签名验证。
以下示例使用.pfx证书在一行代码中签署现有的PDF。
-
1使用 IronPDF 安装 NuGet Package Manager
-
2复制并运行这段代码。
IronPdf.PdfDocument.FromFile("input.pdf").SignWithFile("certificate.pfx", "password").SaveAs("signed.pdf");IronPdf.PdfDocument.FromFile("input.pdf").SignWithFile("certificate.pfx", "password").SaveAs("signed.pdf")IronPdf.PdfDocument.FromFile("input.pdf").SignWithFile("certificate.pfx", "password").SaveAs("signed.pdf") -
3部署到您的生产环境中进行测试
今天就用免费试用在您的项目中开始使用IronPDF
基本流程(5 步)
- 安装 IronPDF for .NET 库。
- 使用
X509Certificate2对象应用数字签名。 - 添加表示数字签名的可视图像。
- 在 PDF 文件上加盖图形或手写签名。
- 添加用于电子签名的交互式签名表单字段。
如何使用证书对 PDF 应用数字签名?
使用证书文件(如.pfx或.p12)制作的数字签名可以识别签名者,并让任何阅读者检测出文件在签署后所做的更改。
IronPDF 提供三种签名方法。 PdfSignature 类包含证书和签名记录的元数据。
| 签名方法 | 说明 |
|---|---|
Sign | 使用您创建和配置的PdfSignature 对象对PDF进行签名。 |
SignWithFile | 使用位于磁盘上的数字签名证书文件(.pfx或.p12)对PDF进行签名。 |
SignWithStore | 按指纹 ID在计算机的证书存储中查找证书,并使用该证书对 PDF 签名。 |
使用X509Certificate2对象
为了获得最大的控制,您可以从证书文件创建一个X509Certificate2对象,并将其传递给PdfSignature。 使用X509KeyStorageFlags.Exportable加载证书,因为签名会导出私钥,如果没有该标志则会失败。 更多数字签名示例可在代码示例部分找到。
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")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 文件加载为证书对象。该对象代表数字身份,随后传入签名构造函数。最后,调用 Sign 对文档签名并保存。有关证书类的详细信息,请参阅Microsoft 官方文档。
IronPDF支持使用RSA和ECDSA证书进行签名。 对于ECDSA证书,将.pfx文件路径或其字节传递给签名构造函数,而不是证书对象。 当一个ECDSA密钥加载到Windows上的证书对象中时,它无法以签名所需的形式导出,并且签名会抛出一个CryptographicException。
在数字签名中添加细节
数字签名除了包含证书外,还可以携带元数据,即签署位置、原因和联系信息,以及来自可信机构的安全时间戳。 这些细节为验证者提供了更完整的审计轨迹。 文档级属性在设置和编辑元数据指南中单独介绍。
以下示例将此元数据、SHA-256签名摘要和来自DigiCert时间戳服务器的时间戳添加到现有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";
// Choose the hash algorithm for the signature digest.
// SHA-256 is the default, and SHA-384 and SHA-512 are also available
signature.SignatureHashAlgorithm = SignatureHashAlgorithms.SHA256;
// Add a secure timestamp from a trusted Time Stamp Authority (TSA).
// This provides cryptographic proof of the signing time.
signature.TimeStampUrl = "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");
有两个独立的设置控制哈希处理。
PdfSignature 属性 | 哈希计算对象 | 取值 |
|---|---|---|
SignatureHashAlgorithm | 签名本身的PKCS#7/CMS摘要 | SHA256, SHA384, SHA512, SHA1 |
TimestampHashAlgorithm | 发送给 TimeStampUrl 指定的时间戳颁发机构的 RFC 3161 消息摘要 | SHA256, SHA512, SHA1 |
签名摘要和时间戳消息印记默认使用 SHA-256。新签名应避免使用密码学强度较低的 SHA-1。示例中的 DigiCert 时间戳服务器会拒绝使用 SHA-1 消息印记的请求。像示例一样显式设置这两个属性,便于审核人员在代码中查看所选算法。
时间戳 URL 以字符串形式指定时间戳颁发机构(TSA)的端点。使用 HSM 签名时也可使用 URL 和时间戳哈希设置,因此用硬件令牌签名的文档同样可以带有可信时间戳。
如果签名证书不在受信任的证书列表中,Adobe Acrobat 等查看器会将签名有效性显示为未知。将证书加入该列表后,查看器会以绿色对勾标示签名有效。
如何为数字签名添加视觉表示?
数字签名存储在文件结构中,并非自动显示在页面上。 要显示它,请将图像附加到PdfSignature对象,例如公司标志或手写签名。
图像可以来自文件或流,并可以放置在任何页面的指定位置。 支持的图像格式包括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")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")这段代码演示了三种等效的图像添加方法:指定文件路径、调用 LoadSignatureImageFromFile 或使用流。图像在签名时绘制到页面上,因此可见签名图像与密码学签名会一起应用。
如何在现有的命名签名字段中签名?
拿到的表单可能已放置并命名了签名栏。例如,政府表单可能
分别为填报人和审批人预留签名栏。将
SignatureFieldName 设为其中一个字段的名称,IronPDF 即可在原位置签名,
沿用表单作者设定的位置和外观,无需追加新字段。
using IronPdf;
using IronPdf.Signing;
// A form that already contains named signature blocks
PdfDocument pdf = PdfDocument.FromFile("dd-form-200.pdf");
PdfSignature signature = new PdfSignature("cert.pfx", "password")
{
// Name of an existing, unsigned signature field
SignatureFieldName = "ApproverSignature"
};
// Fills that field where the form author placed it
pdf.Sign(signature);
pdf.SaveAs("signed.pdf");
使用文档中签名表单字段的 Name 值。如果字段名称未设置、为空
或仅包含空白字符,签名时仍会照常追加一个新字段。
如果找不到指定名称的未签名字段,或同名字段都已签名,签名操作 会抛出异常。错误消息会列出字段名称,便于定位拼写错误。
签名时若需追加新字段,IronPDF 会按 Signature1、Signature2 等顺序命名,
并跳过文档中已使用的名称。例如,表单中已有名为 Signature1 的未签名占位字段时,
该字段会保留,追加的签名字段将命名为 Signature2。
在命名字段中签名时,SignaturePermissions 不生效。预置字段中的签名
始终是普通的批准签名,不附带认证权限,因此同时传入的权限值
会被忽略。认证权限仅在签名操作追加新字段时适用。
ISO 32000 还要求认证签名必须位于文档中第一个
已签名的字段。
使用 IronPdfEngine 或 Docker 部署时,所用的引擎版本必须包含此功能。 较旧的引擎无法识别字段名称,会直接追加新字段而不发出提示, 原有的命名签名栏仍为空。因此,请确保引擎版本与库版本匹配。
SignatureImage签署命名字段。 应用图像会重新定位 字段,这会移动表单作者放置的块,因此组合会引发 NotSupportedException. 签署命名字段而不使用图像,或将字段名称留空以 添加一个可以自由定位的新字段。签署后如何控制文档权限?
当您签署文档时,您可以指定之后允许的更改(如果有)。 例如,您可以完全锁定文档,或仅允许填写表单和添加额外的签名。 IronPDF通过SignaturePermissions枚举设置这些权限,作为第二个参数传递给Sign。 当省略时,签名适用NoChangesAllowed。 有关基于密码的限制,请参阅 设置 PDF 密码和权限指南。
这些值是 ISO 32000 定义的标准 PDF DocMDP 认证权限,会写入签名。每个值规定后续签名方可在保持当前签名有效的前提下对文档执行哪些操作。符合标准的阅读器会将任何其他更改视为使该签名失效。
SignaturePermissions 成员 | DocMDP 级别 | 后续操作方可执行的操作 |
|---|---|---|
NoChangesAllowed | 1 | 不允许任何更改,文档相当于被锁定。 |
AdditionalSignaturesAndFormFillingAllowed | 2 | 添加另一个签名并填写表单字段。 |
AdditionalSignaturesFormFillingAndAnnotationsAllowed | 3 | 添加另一个签名、填写表单字段以及创建或修改注释。 |
VerifyPdfSignatures 验证每个签名的字节范围,而不是其权限级别,因此请在符合要求的阅读器中检查权限限制,例如Adobe Acrobat。每次保存可以添加多少个签名?
PdfDocument 每次保存只接受一个新签名。在同一个已打开的文档中
添加第二个签名时,会立即抛出 NotSupportedException。
增量保存也遵循这一规则。
这是由 PDF 签名机制决定的。签名覆盖文件中截至其自身占位位置的内容, 因此,在同一修订版中添加第二个签名会改变第一个签名已覆盖的字节。 这样只有最后一个签名能通过验证。早期版本允许这种操作, 因此生成的文档中,较早的签名会在没有提示的情况下失效。 现在签名操作会拒绝这种用法。
因此,pdf.Sign(a).Sign(b).SaveAs(...) 已无法使用。对同一个对象
调用两次签名方法也会失败。
多个方如何签署同一份文件?
支持多方签名。同一个文档可以包含多个签名,规则是每个修订版一个签名。 在以下示例中,各方分别在自己的增量修订版中签名。
using IronPdf.Signing;
PdfDocument.FromFile("form.pdf")
.Sign(signatureA, SignaturePermissions.AdditionalSignaturesAndFormFillingAllowed)
.SaveAs("step1.pdf");
PdfDocument.FromFile("step1.pdf").Sign(signatureB).SaveAsRevision("step2.pdf");
修订历史记录会包含两个修订版,各有一个签名,且两个签名均可通过验证。
第一个签名上的 AdditionalSignaturesAndFormFillingAllowed 权限允许第二方
追加修订版,同时保持第一个签名有效。
增量保存使这一流程成为可能。每次保存都会追加一个新修订版,并保留 已有字节。第二方保存时会将签名写入新修订版,因此第一个签名 仍覆盖它签过的字节,文档可以依次通过多个审批环节。 Adobe Acrobat 可以比较签名所覆盖的版本与当前版本, 显示应用该签名后发生的更改。有关增量保存的详细信息, 请参阅 PDF 修订历史记录管理指南。
SaveAsRevision("step2.pdf") 将修订直接写入磁盘。 调用时没有路径,它 返回内存中的修订,以便稍后SaveAs.。
如何管理和验证跨修订版的签名?
PDF文档可以在多个修订版本中携带签名。 IronPDF提供以下方法用于处理该历史记录。
- 回滚到之前的修订版。
GetRevision方法将文档返回到之前修订时的状态,作为一个单独的文档,不包含之后添加的更改和签名。RevisionCount报告文件包含多少次修订。 - 验证所有签名。
VerifyPdfSignatures方法检查文档所有修订中的_所有_签名。 仅当每个签名都有效时,它返回 true;如果任何签名无效或文档没有签名,则返回 false。 静态PdfDocument.VerifyPdfSignaturesInFile方法在不加载完整文档的情况下对文件路径进行相同的检查。 - 检测增量篡改。
detectIncrementalTampering参数添加了修订级别的篡改检查。 默认情况下它是关闭的,因为这会增加处理时间。 - 删除签名。
RemoveSignatures方法从文档的每个修订版中去除所有数字签名,创建一个干净的、未签名的版本。
除了上述验证方法,GetVerifiedSignatures 也支持篡改检查。它可检测影子攻击,即利用后续增量更新悄悄重新定义较早签名所覆盖的对象。处理大型文档或修订次数较多的文档时,额外开销最明显。IronPDF API 参考文档建议在法律和政府场景下的多签名工作流中启用此检查。
// 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.VerifyPdfSignatures(detectIncrementalTampering: true);
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");
如何在 PDF 上加盖手写签名?
某些文档需要可见签名而不需要数字签名的加密安全性,例如放置在发票上的扫描手写签名。这称为盖章,IronPDF通过HtmlStamper类和ApplyStamp方法来实现。 有关更多盖章和水印选项,请参见自定义水印指南。
示例从一个发票PDF样本和一个手写签名的PNG图像开始。
加盖签名前的原始发票 PDF。
以下图像是需要应用的签名。
手写签名图像示例。
以下代码将签名图像放入 HTML 图章,并加盖到每一页的右下角。
using IronPdf;
using IronPdf.Editing;
// Load the existing PDF document.
var pdf = PdfDocument.FromFile("invoice.pdf");
// Create an HtmlStamper containing our signature image.
// HtmlStamper allows us to position HTML content precisely on the page
var signatureStamp = new HtmlStamper("<img src='assets/signature.png'/>")
{
// Configure the stamp's position and appearance.
VerticalAlignment = VerticalAlignment.Bottom,
HorizontalAlignment = HorizontalAlignment.Right,
HorizontalOffset = new Length(-10, MeasurementUnit.Pixel), // Add some space from the edge.
VerticalOffset = new Length(-10, MeasurementUnit.Pixel),
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;
using IronPdf.Editing;
// Load the existing PDF document.
var pdf = PdfDocument.FromFile("invoice.pdf");
// Create an HtmlStamper containing our signature image.
// HtmlStamper allows us to position HTML content precisely on the page
var signatureStamp = new HtmlStamper("<img src='assets/signature.png'/>")
{
// Configure the stamp's position and appearance.
VerticalAlignment = VerticalAlignment.Bottom,
HorizontalAlignment = HorizontalAlignment.Right,
HorizontalOffset = new Length(-10, MeasurementUnit.Pixel), // Add some space from the edge.
VerticalOffset = new Length(-10, MeasurementUnit.Pixel),
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
Imports IronPdf.Editing
' Load the existing PDF document.
Dim pdf = PdfDocument.FromFile("invoice.pdf")
' Create an HtmlStamper containing our signature image.
' HtmlStamper allows us to position HTML content precisely on the page
Dim signatureStamp = New HtmlStamper("<img src='assets/signature.png'/>") With {
' Configure the stamp's position and appearance.
.VerticalAlignment = VerticalAlignment.Bottom,
.HorizontalAlignment = HorizontalAlignment.Right,
.HorizontalOffset = New Length(-10, MeasurementUnit.Pixel), ' Add some space from the edge.
.VerticalOffset = New Length(-10, MeasurementUnit.Pixel),
.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
Imports IronPdf.Editing
' Load the existing PDF document.
Dim pdf = PdfDocument.FromFile("invoice.pdf")
' Create an HtmlStamper containing our signature image.
' HtmlStamper allows us to position HTML content precisely on the page
Dim signatureStamp = New HtmlStamper("<img src='assets/signature.png'/>") With {
' Configure the stamp's position and appearance.
.VerticalAlignment = VerticalAlignment.Bottom,
.HorizontalAlignment = HorizontalAlignment.Right,
.HorizontalOffset = New Length(-10, MeasurementUnit.Pixel), ' Add some space from the edge.
.VerticalOffset = New Length(-10, MeasurementUnit.Pixel),
.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 IronSoftware.Forms;
// 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
uint pageIndex = 0; // Add to the first page (zero-indexed)
// Create the SignatureFormField object.
// This creates an interactive field that users can click to sign
var signatureField = new SignatureFormField(fieldName, pageIndex, 50, 200, 300, 100); // Position: (x, y), Size: (width, height)
// 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 文档中的交互式签名字段,尚未签名。
如何从已验证的签名中检索签名人姓名?
要获取签名者的姓名,请读取 VerifiedSignature 类的 SignerName 属性,如以下代码所示。
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}");
});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)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()方法来检索已验证签名的列表,并输出每个签名者的姓名。
优先从签名字典中读取签名者姓名,其次使用证书主体可分辨名称(SubjectDN)中的 CN 字段。如果两个来源都没有值,则返回空字符串。
每个已验证的签名还提供 Valid 和 Status,用于查看验证结果。SignerCertificate 提供签名证书的完整 X.509 信息,包括主体和颁发者的可分辨名称(DN)、序列号、有效期和 SHA-256 指纹。CertificateChain 提供从签名者证书到根证书的证书链。有关提取国家身份标识、证书固定和遍历证书链的详细信息,请参阅从已验证的 PDF 签名中读取签名者证书指南。
使用IronPDF进行 PDF 签名的下一步是什么?
本指南介绍了带元数据和时间戳的证书数字签名、签名权限、跨修订版的多方签名、签名验证、加盖手写签名以及交互式签名字段。
要在您自己的项目中尝试这些示例,请下载IronPDF库并获取免费试用许可证。 相关指南涵盖了添加注释和处理表单字段,签名和保护PDF教程结合了签名、密码和权限。 IronPDF也是Iron Suite的一部分,该套件将十个Iron Software .NET库打包在一个许可证密钥下作为一次性购买。
常见问题
如何使用IronPDF和证书为PDF数字签名?
将证书加载到具有Exportable存储标志的X509Certificate2对象中,传递给新的PdfSignature,并在保存之前对PdfDocument调用Sign。SignWithFile通过从.pfx或.p12路径中进行一次调用来完成相同操作,SignWithStore使用由其指纹识别的证书存储中的证书进行签名。
在IronPDF中,添加图像作为数字签名的步骤是什么?
使用您的证书创建一个PdfSignature并为其SignatureImage属性分配一个PdfSignatureImage,提供页面索引以及用于定位和尺寸的矩形。LoadSignatureImageFromFile和LoadSignatureImageFromStream可以从文件路径或者流中加载签名图像。支持PNG、JPEG、GIF、BMP、TIFF和WebP格式的图像,图像将在文档签署时绘制到页面上。
我可以在IronPDF中为PDF添加交互式签名字段吗?
是的。创建一个SignatureFormField,指定名称、页码索引、位置和大小,然后使用pdf.Form.Add将其添加到文档中。保存的PDF包含一个空的、可点击的签名字段,接收者可以在Adobe Acrobat等查看器中签署。
IronPDF提供了哪些方法来验证PDF文档中的所有签名?
VerifyPdfSignatures 会检查每个修订中的每个签名,并仅在所有签名有效时返回 true。PdfDocument.VerifyPdfSignaturesInFile 会在文件路径上运行相同的检查。有关每个签名的详细信息,GetVerifiedSignatures 会为每个签名返回一个 VerifiedSignature。将任一方法的 detectIncrementalTampering 参数设置为 true,将增加一个修订级别的分析,以检测在应用早期签名后重新定义的对象。
我可以如何在使用IronPDF签名PDF后管理文档权限?
将 SignaturePermissions 值作为第二个参数传递给 Sign。NoChangesAllowed 锁定文档且为默认选项,AdditionalSignaturesAndFormFillingAllowed 允许进一步签名和表单填写,而 AdditionalSignaturesFormFillingAndAnnotationsAllowed 还允许注释。 这些值是 ISO 32000 定义的 DocMDP 等级 1、2 和 3,符合此标准的 PDF 阅读器会执行这些限制。
IronPDF 使用哪些哈希算法进行签名和时间戳?
SignatureHashAlgorithm设置签名摘要,并接受SHA-256、SHA-384、SHA-512或SHA-1。TimestampHashAlgorithm设置发送到TimeStampUrl中的时间戳机构的RFC 3161印记,并接受SHA-256、SHA-512或SHA-1。两者默认为SHA-256。SHA-1在密码学上较弱,不应用于新的签名,包括DigiCert在内的一些时间戳机构会拒绝它。
IronPDF提供了什么功能用于将手写签名添加到PDF中?
使用HtmlStamper类与指向签名图像的图像标签,设置其对齐方式和偏移量,并用ApplyStamp应用它。结果是一个可视签名的PDF,但没有数字签名的加密保护。要将可见图像与数字签名结合,请使用PdfSignature的SignatureImage属性。
如何在PDF中通过IronPDF从已验证的签名中检索签名者的名称?
调用GetVerifiedSignatures,该方法返回一个VerifiedSignature对象的列表,并读取每个对象的SignerName属性。签名者的名称来源于存储在签名字典中的名称,如果没有则使用证书主体的CN字段作为备用。SignerCertificate和CertificateChain提供完整的证书详细信息和到根的链。
在IronPDF中是否可能回滚到已签署PDF文档的先前版本?
是的。GetRevision 返回一个经过签名的PDF,它表示在早期修订时期的状态,作为一个独立的 PdfDocument,不包含之后添加的更改和签名。而 RevisionCount 则报告存在多少次修订。这在包含多个审批阶段的工作流程中,审核早期文档状态时非常有用。
使用IronPDF进行PDF签名应采取哪些步骤?
从NuGet安装IronPdf包,并从本页的一行SignWithFile示例开始。 提供免费试用许可证,供您在自己的项目中测试电子和视觉签名、签名字段和签名验证。 IronPDF代码示例和"签名和保护PDF"教程更深入地涵盖了相同的功能。
如何在PDF中登录到现有命名的签名字段?
在PdfSignature上设置SignatureFieldName属性为现有的、未签名的签名表单字段的名称。IronPDF将填充表单作者放置的位置,而不是附加新的,这正是具有多个命名签名块的表单所需的。如果不存在具有该名称的未签名字段,签名将抛出异常,并且错误消息中会提及该字段。SignatureFieldName不能与SignatureImage结合使用,因为应用图像会重新定位字段。
为什么对PDF进行两次签名会引发NotSupportedException异常?
PdfDocument每次保存都会添加一个新签名。在同一次修订中添加第二个签名会更改第一个已签名的字节,因此只有最后一个签名可以验证。早期版本允许这样做,并会生成具有无效签名的文档,而当前版本则会抛出错误。要让多方签名,您需要签名并保存,然后重新打开文件,并通过SaveAsRevision添加下一个签名,遵循每次保存一个签名的模式。
SignaturePermissions和"每次保存一个签名"规则之间有什么区别?
它们是独立的概念。 SignaturePermissions 是由 ISO 32000 定义的标准 PDF 认证权限。它被写入已签名的文档中,并管理后续方在不使签名失效的情况下可以更改的内容。每次保存一个签名的规则管理在单次保存之前可以批量进行多少次 Sign() 调用。允许附加签名的权限并不允许在一次保存中有两个签名。
签名权限在签署指定字段时是否适用?
不。填充预先放置的字段始终会生成一个普通的批准签名,并且不附带任何认证权限,因此与SignatureFieldName一起传递的权限值没有效果。要对文档进行认证并赋予权限,请在没有字段名称的情况下应用第一个签名,以便签名附加一个新字段。
Jacob Mellor是Iron Software的首席技术官,也是C# PDF技术的先锋工程师。作为Iron Software核心代码库的原始开发者,自公司成立以来,他就一直在塑造公司的产品架构,与首席执行官Cameron Rimington一起将其转型为拥有50多人、服务于NASA、特斯拉和全球政府机构的公司。