ITextsharp 在使用线条或矩形时使签名无效

本文关键字:无效 ITextsharp | 更新日期: 2023-09-27 18:32:42

当我使用 ITextSharp 对已经使用此代码进行数字签名的文档进行数字签名时,它会使其他签名无效。如果我使用文本或图像进行数字签名,它可以正常工作。这是Adobe/Itextsharp的限制还是代码有问题?

public void SignWithLine(string pdfFilePath, string outputFilePath, LineAnnotation lineAnnotation)
{        
    double xStartPoint = 89.285969238281268, yStartPoint = 343.08978515624881, xEndPoint = 72.7515234375, yEndPoint = 496.03341796874878, lineStroke = .24;
    CertificateWrapper certificate = CertificateWrapper.GetCertificateInformationFromSignature(GetCertificateInformation());
    PdfReader reader = new PdfReader(pdfFilePath);
    PdfTemplate layer = null;
    using (PdfStamper signature = PdfStamper.CreateSignature(reader, null, ''0', outputFilePath, true))
    {
        PdfSignatureAppearance signatureAppearance = signature.SignatureAppearance;
        signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC;
        Rectangle rect = new Rectangle((float)Math.Min(xStartPoint, xEndPoint), (float)Math.Min(yStartPoint, yEndPoint), (float)Math.Min(xStartPoint, xEndPoint) + (float)Math.Abs(xEndPoint - xStartPoint), (float)Math.Min(yStartPoint, yEndPoint) + (float)Math.Abs(yEndPoint - yStartPoint));
        signatureAppearance.SetVisibleSignature(rect, lineAnnotation.PageIndex + 1, GetCertificateFieldName());
        layer = signatureAppearance.GetLayer(2);
        PdfContentByte cb = signature.GetUnderContent(lineAnnotation.PageIndex + 1);
        cb.SetLineWidth((float)lineStroke);
        cb.MoveTo((float)xStartPoint, (float)yStartPoint);
        cb.LineTo((float)(xEndPoint), (float)(yEndPoint));
        cb.Stroke();
        signatureAppearance.CertificationLevel = PdfSignatureAppearance.NOT_CERTIFIED;
        // Normal signature, not a certification
        MakeSignature.SignDetached(signatureAppearance, certificate.DigitalSignature, certificate.Chain, null, null, null, 0, true);
        signature.Close();
    }
}

ITextsharp 在使用线条或矩形时使签名无效

>signature是你的PdfStamper。你在上面画一条线

PdfContentByte cb = signature.GetUnderContent(lineAnnotation.PageIndex + 1);

即您在页面的内容流中绘制它。这算作页面内容的更改,因此原始签名禁止更改。有关允许更改的详细信息,请参阅此答案。

我找到了一种方法,通过修改iTextSharp库来做到这一点。

首先,我重载了 SetVisibleSignature 以传递 int 列表

public void SetVisibleSignature(Rectangle pageRect, String fieldName, List pageList({页面 = 页面列表;页面是私有列表页面;...}

其次,在预收盘事件中,您按如下所示更新它

            sigField.Page = pagen;
            if (pagen != 0)
                writer.AddAnnotation(sigField, pagen);
           else if (pages != null && pages.Count > 0) 
                pages.ForEach(f => writer.AddAnnotation(sigField, f)); // this annotates all pages with the same signature
            else
                throw new DocumentException("No pages specified for signature.");