Search code examples
c#pdfitext

"At least one signature is invalid" After adding stamp in Signed PDF


I need to add stamp or image annotation in a signed PDF but it gives me an "invalid signature" error and, after moving this annotation, it gives me an "at least one signature required validating" error. How can I solve this?

I also found a solution but for text annotation in this question. It worked fine with text annotation but I cannot do the same for the stamp.

iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(@"D:\\11.jpg");
float w = 100;
float h = 100;
iTextSharp.text.Rectangle location = new iTextSharp.text.Rectangle(36, 770 - h, 36 + w, 770);

PdfAnnotation stamp = PdfAnnotation.CreateStamp(stamper.Writer, location, null, "ITEXT");
img.SetAbsolutePosition(0, 0);
PdfContentByte cb = stamper.GetOverContent(1);
PdfAppearance app = cb.CreateAppearance(100, 100);
app.AddImage(img);
stamp.SetAppearance(PdfName.N, app);
stamper.AddAnnotation(stamp, 1);

Solution

  • This

    PdfContentByte cb = stamper.GetOverContent(1);
    

    is the line causing the invalidation of the signature.

    Calling stamper.GetOverContent (or stamper.GetUnderContent) already prepares the page contents for the addition of new content. This preparation already is considered a change of page content. As page content changes to a signed PDF are forbidden, this invalidates the signature.

    You only use this PdfContentByte cb to create a PdfAppearance for your stamp annotation:

    PdfAppearance app = cb.CreateAppearance(100, 100);
    

    Fortunately you don't need cb to create a PdfAppearance, there also is a static PdfAppearance method to do so. Thus, simply replace

    PdfContentByte cb = stamper.GetOverContent(1);
    PdfAppearance app = cb.CreateAppearance(100, 100);
    

    by

    PdfAppearance app = PdfAppearance.CreateAppearance(stamper.Writer, 100, 100);