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

如何用iText库在带数字签名的PDF中添加水印且不使签名失效

关于iText给带签名PDF添加水印且保留签名的实现

核心说明

iText完全支持通过增量更新实现带签名PDF的水印添加,这种方式不会修改原有签名覆盖的字节区域,因此签名不会失效。增量更新是PDF规范允许的合法操作,仅在文档末尾追加新的修改内容。

C#示例代码

以下是完整的实现示例,给已签名PDF添加文本水印:

using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;
using System.IO;

class SignedPdfWatermarker
{
    static void Main(string[] args)
    {
        string inputPath = "signed_input.pdf";
        string outputPath = "signed_with_watermark.pdf";

        // 以只读模式打开原有签名PDF,避免修改核心内容
        using (PdfReader reader = new PdfReader(inputPath))
        {
            // 启用增量更新模式,所有修改将追加到文档末尾
            using (PdfWriter writer = new PdfWriter(outputPath).SetAppendMode())
            {
                using (PdfDocument pdfDoc = new PdfDocument(reader, writer))
                {
                    Document document = new Document(pdfDoc);
                    int pageCount = pdfDoc.GetNumberOfPages();

                    // 遍历每一页添加水印
                    for (int i = 1; i <= pageCount; i++)
                    {
                        var pageSize = pdfDoc.GetPage(i).GetPageSize();
                        float pageWidth = pageSize.GetWidth();
                        float pageHeight = pageSize.GetHeight();

                        // 创建半透明倾斜水印
                        Paragraph watermark = new Paragraph("CONFIDENTIAL")
                            .SetFontSize(40)
                            .SetOpacity(0.2f)
                            .SetTextAlignment(TextAlignment.CENTER);

                        // 将水印居中倾斜添加到页面,不遮挡原有内容和签名
                        document.ShowTextAligned(watermark, 
                            pageWidth / 2, pageHeight / 2, 
                            i, TextAlignment.CENTER, VerticalAlignment.MIDDLE, 45);
                    }

                    document.Close();
                }
            }
        }
    }
}

关键注意事项

  • 必须调用SetAppendMode()启用增量更新,这是保证签名不失效的核心
  • 仅允许追加新内容(如水印),禁止修改原有页面的任何元素(包括签名区域)
  • 水印建议设置低透明度,避免遮挡原有签名和文档内容
  • 始终以只读模式打开源PDF,防止误操作破坏签名字节范围

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 03:52:02