You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PDFSharp-Extended 1.0.1添加PDF数字签名遇构造函数错误求助

解决PDFSharp-Extended 1.0.1中PdfSignatureField构造函数错误

错误原因

你遇到的CS1729错误是因为PDFSharp-Extended 1.0.1版本的PdfSignatureField类,并没有提供接收(PdfPage, string)两个参数的构造函数,当前调用方式不符合类的定义。

修正后的代码

以下是调整后的完整代码,修复了构造函数问题,同时补充了AcroForm判空逻辑(避免原PDF无表单时的异常):

using System;
using System.Security.Cryptography.X509Certificates;
using PdfSharp.Pdf;
using PdfSharp.Pdf.AcroForms;
using PdfSharp.Pdf.IO;
using PdfSharp.Pdf.Security;

class Program
{
    static void Main()
    {
        string inputPdfPath = "input.pdf";
        string outputPdfPath = "output.pdf";
        string privateKeyPath = "privatekey.pfx";
        string privateKeyPassword = "password";

        PdfDocument document = PdfReader.Open(inputPdfPath, PdfDocumentOpenMode.Modify);

        // 确保文档存在AcroForm,不存在则创建
        if (document.AcroForm == null)
        {
            document.AcroForm = new PdfAcroForm(document);
        }

        // 初始化签名字段,改用无参构造
        PdfSignatureField signatureField = new PdfSignatureField();
        // 设置字段所属页面
        signatureField.Page = document.Pages[0];
        // 设置字段唯一名称
        signatureField.Name = "Signature";
        // 绑定PFX证书签名处理器
        signatureField.SignatureHandler = new X509Certificate2SignatureHandler(privateKeyPath, privateKeyPassword);

        document.AcroForm.Fields.Add(signatureField);
        document.Save(outputPdfPath);

        Console.WriteLine("PDF signed successfully.");
    }
}

关键调整说明

  • 替换PdfSignatureField构造方式:使用无参构造后,手动设置Page和Name属性,这是该版本类支持的正确用法。
  • 添加AcroForm判空逻辑:如果原PDF没有交互式表单,直接添加字段会引发异常,因此先检查并创建AcroForm。

内容的提问来源于stack exchange,提问作者Gaurav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 14:24:59