Add multiple Digital Signature in PDF using iTextSharp in C#

拈花ヽ惹草 提交于 2019-12-06 07:55:18

问题


I have implemented Digital Signature using iTextSharp Dll to sign PDF files with a single signature. Now, I want to add another digital signature in previously or already digitally signed PDF and I’m getting an error when verifying one signature.

How can I add multiple Digital Signature in one PDF and verify all signatures.

I’m using the following code:

PdfReader reader = new PdfReader(fileName);
using (FileStream fout = new FileStream(SignedFileName, FileMode.Create, FileAccess.ReadWrite))
{
    // appearance
    PdfStamper stamper = PdfStamper.CreateSignature(reader, fout, '\0');
    PdfSignatureAppearance appearance = stamper.SignatureAppearance;
    //appearance.Reason = SignReason;
    //appearance.Location = SignLocation;
    appearance.SignDate = DateTime.Now.Date;
    appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(xPos, yPos, xPos + 200, yPos + 100), PageNo, null);//.IsInvisible

    // Custom text and background image
    appearance.Image = iTextSharp.text.Image.GetInstance(SignatureImg);
    appearance.ImageScale = 0.6f;
    appearance.Image.Alignment = 300;
    appearance.Acro6Layers = true;

    StringBuilder buf = new StringBuilder();
    buf.Append("Digitally Signed by ");
    String name = SignerName;

    buf.Append(name).Append('\n');
    buf.Append("Date: ").Append(DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss zzz"));

    string text = buf.ToString();

    appearance.Layer2Text = text;

    //digital signature
    IExternalSignature es = new PrivateKeySignature(pk, "SHA-256");
    MakeSignature.SignDetached(appearance, es, new Org.BouncyCastle.X509.X509Certificate[] { pk12.GetCertificate(alias).Certificate }, null, null, null, 0, CryptoStandard.CMS);

    stamper.Close();

}

回答1:


The error is in this line:

PdfStamper stamper = PdfStamper.CreateSignature(reader, fout, '\0');

Change it to:

PdfStamper stamper = PdfStamper.CreateSignature(reader, fout, '\0', true);

The explanation: you are not signing the document in append mode.

On further inspection of your code, I see that you're also adding an image. That can be tricky. Adding the new signature in append mode solves one problem. Adding that extra content could cause an extra problem depending on the version of iText you are using.



来源:https://stackoverflow.com/questions/41734958/add-multiple-digital-signature-in-pdf-using-itextsharp-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!