Add multiple Digital Signature in PDF using iTextS

2020-07-23 05:22发布

问题:

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.