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

使用iTextSharp创建PDF文件时是否可以同步添加数字签名?

iTextSharp生成PDF过程中追加数字签名的实现方案

该操作完全可以实现,你不需要落地生成中间PDF文件再读取,直接用内存流转接即可适配PdfStamper.CreateSignature的参数要求,具体实现逻辑如下:

核心实现思路

你完成所有PDF普通内容的编写逻辑后,先把当前生成的PDF内容写入内存流,再用内存流的内容初始化PdfReader实例,即可传入签名方法完成末尾追加签名,整个过程可以完全在内存中完成,不需要磁盘IO操作。

代码示例

using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.security;
using Org.BouncyCastle.Pkcs;
using System.IO;
using System.Linq;

// 1. 生成PDF普通内容,写入内存流
using (var contentMs = new MemoryStream())
{
    var document = new Document();
    PdfWriter.GetInstance(document, contentMs);
    document.Open();

    // 此处添加你所有的PDF业务内容,比如段落、表格、图片等
    document.Add(new Paragraph("待签名的PDF业务内容"));

    document.Close();

    // 2. 用已生成的PDF内容初始化PdfReader
    byte[] pdfContent = contentMs.ToArray();
    using (var reader = new PdfReader(pdfContent))
    {
        // 3. 定义签名后文件的输出流,可根据需求用文件流或内存流
        using (var outputFs = new FileStream("signed.pdf", FileMode.Create, FileAccess.Write))
        {
            // 4. 调用CreateSignature方法,最后一个参数传true启用追加模式,签名会写入PDF末尾
            PdfStamper stamper = PdfStamper.CreateSignature(reader, outputFs, '\0', null, true);
            PdfSignatureAppearance appearance = stamper.SignatureAppearance;

            // 配置签名基础信息
            appearance.Reason = "文档身份验证";
            appearance.Location = "本地";
            // 配置签名可见区域:坐标、页码、签名域名称
            appearance.SetVisibleSignature(new Rectangle(50, 50, 250, 150), 1, "DigitalSignature");

            // 加载PFX格式的数字证书
            var pfxStream = new FileStream("your_cert.pfx", FileMode.Open, FileAccess.Read);
            var pfxStore = new Pkcs12Store(pfxStream, "your_cert_password".ToCharArray());
            string keyAlias = pfxStore.Aliases.Cast<string>().FirstOrDefault(a => pfxStore.IsKeyEntry(a));
            var privateKey = pfxStore.GetKey(keyAlias).Key;
            var certChain = pfxStore.GetCertificateChain(keyAlias).Select(c => c.Certificate).ToArray();

            // 执行签名
            MakeSignature.SignDetached(
                appearance,
                new BouncyCastleDigest(),
                privateKey,
                certChain,
                null, null, null,
                0,
                CryptoStandard.CMS
            );
        }
    }
}

注意事项

  • 如果处理大体积PDF,你可以直接将内存流的Position重置为0后传入PdfReader,不需要调用ToArray()生成中间字节数组,可大幅降低内存占用。
  • PdfStamper.CreateSignature的第5个布尔参数设为true时,会启用PDF增量更新模式,签名内容会直接追加到文件末尾,不会修改原PDF的任何已有内容,完全符合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 14:39:01