如何在 C# 中为 PDF 添加数字签名

本基本指南重点介绍如何在 C# 中向 PDF 添加数字签名。数字签名功能可用于验证 PDF 内容以及避免任何修改。这些精确的步骤和代码示例解释了如何使用 C# 向 PDF 文件添加签名。

在 C# 中向 PDF 添加数字签名的步骤

  1. 添加对 Aspose.PDF for .NET 库的引用以在您的应用程序中对 PDF 进行数字签名
  2. PKCS7 类对象中加载输入 PDF document 和证书文件
  3. 设置页面直角坐标和外观图片放置签名
  4. 认证 PDF 文件以完成文档签名过程
  5. 将带有签名的输出PDF文件保存在指定位置

这些步骤阐明了如何使用 C# 向 PDF 文件添加签名。您可以在加载输入图像时将外观图像自定义为手写签名。此外,还需要证书文件及其密码来证明数字签名的真实性。

在 C# 中向 PDF 添加数字签名的代码

using Aspose.Pdf;
namespace AddDigitalSignatureToPDFInCSharp
{
class Program
{
static void Main(string[] args) // Main function to add digital signature to PDF in CSharp
{
// Instantiate the license object to avoid trial version limitations and watermark in output PDF file
Aspose.Pdf.License licDigitalSignature= new Aspose.Pdf.License();
licDigitalSignature.SetLicense("Aspose.Pdf.lic");
// Load the source PDF document for adding the digital signature
Document doc = new Document("input.pdf");
// Instantiate the PdfFileSignature for the loaded PDF document
Aspose.Pdf.Facades.PdfFileSignature signature = new Aspose.Pdf.Facades.PdfFileSignature(doc);
// Load the certificate file along with the password
Aspose.Pdf.Forms.PKCS7 pkcs = new Aspose.Pdf.Forms.PKCS7("certificate1.pfx", "123456789");
// Assign the access permissions
Aspose.Pdf.Forms.DocMDPSignature docMdpSignature = new Aspose.Pdf.Forms.DocMDPSignature(pkcs, Aspose.Pdf.Forms.DocMDPAccessPermissions.FillingInForms);
// Set the rectangle for the signature placement
System.Drawing.Rectangle rect = new System.Drawing.Rectangle(150, 650, 450, 150);
// Set signature appearance
signature.SignatureAppearance = "aspose-logo.png";
// Sign the PDF file with the certify method
signature.Certify(1, "Signature Reason", "Contact", "Location", true, rect, docMdpSignature);
// Save digitally signed PDF file
signature.Save("Digitally Signed PDF.pdf");
System.Console.WriteLine("Done");
}
}
}

上面的代码片段显示了如何将使用 C# 数字签名 PDF 功能集成到您的应用程序中。 PdfFileSignature 类对象用于处理签名的不同属性。例如,修订或用户权限信息、用于在 PDF 文件中添加或删除数字签名的访问权限等。

在本文中,我们学习了如何在 C# 中为 PDF 添加数字签名。但是,如果您想学习如何保护 PDF 文件,请参阅 如何在 C# 中使用密码保护 PDF 上的文章。

 简体中文