Search code examples
c#asp.netasp.net-mvc-4itextsign

How to check if a PDF file is signed or not using iTextsharp in C#?


I have a PDF file and I want to check whether it is signed by digital signature or not. using iTextsharp, the code in C#.


Solution

  • I would advise taking a look at the official examples.

    They contain e.g. an example "SignatureInfo" which outputs multiple information items on all signatures embedded in a PDF; thus, they in particular determine whether a file is signed at all.


    It you are using iTextSharp 5.5.x, your pivotal code is this

    public void InspectSignatures(String path) {
        Console.WriteLine(path);
        PdfReader reader = new PdfReader(path);
        AcroFields fields = reader.AcroFields;
        List<String> names = fields.GetSignatureNames();
        SignaturePermissions perms = null;
        foreach (String name in names) {
            Console.WriteLine("===== " + name + " =====");
            perms = InspectSignature(fields, name, perms);
        }
        Console.WriteLine();
    }
    

    (from the iTextSharp example C5_02_SignatureInfo.cs)

    As you see, the method AcroFields.GetSignatureNames() gets you the names of all signed signature fields. If that list is non-empty, the PDF is signed.


    If you are using iText 7 for .Net, your pivotal code is this:

    public virtual void InspectSignatures(String path)
    {
        // System.out.println(path);
        PdfDocument pdfDoc = new PdfDocument(new PdfReader(path));
        PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, false);
        SignaturePermissions perms = null;
        SignatureUtil signUtil = new SignatureUtil(pdfDoc);
        IList<String> names = signUtil.GetSignatureNames();
        foreach (String name in names)
        {
            System.Console.Out.WriteLine("===== " + name + " =====");
            perms = InspectSignature(pdfDoc, signUtil, form, name, perms);
        }
        System.Console.Out.WriteLine();
    }
    

    (from the iText 7 for .Net example C5_02_SignatureInfo.cs)

    As you see, the method SignatureUtil.GetSignatureNames() gets you the names of all signed signature fields. If that list is non-empty, the PDF is signed.


    By the way, as you did not specify any further, I assume you mean regular integrated PDF signatures, in particular neither detached signatures nor XFA signatures.