Get all certificates in a PDF signature

Spire.PDF allows getting and verifying a specific signature in a PDF file, now starts from version 3.8.82, Spire.PDF supports to get all certificates in a PDF signature. In this article, we will show you the steps of how to achieve this task by using Spire.PDF.

For demonstration, we used a template PDF file which contains two certificates:

How to get all certificates in a PDF signature

Code snippets:

Step 1: Instantiate a PdfDocument object and load the PDF file.

PdfDocument doc = new PdfDocument();
doc.LoadFromFile("UPS.pdf");

Step 2: Create a List object.

List<PdfSignature> signatures = new List<PdfSignature>();

Step 3: Get all signatures from the PDF file and add them into the list object.

var form = (PdfFormWidget)doc.Form;
for (int i = 0; i < form.FieldsWidget.Count; ++i)
{
    var field = form.FieldsWidget[i] as PdfSignatureFieldWidget;
    if (field != null && field.Signature != null)
    {
        PdfSignature signature = field.Signature;
        signatures.Add(signature);
    }
}

Step 4: Get the first signature from the list, and then get all the certificates from the signature.

PdfSignature signatureOne = signatures[0];
X509Certificate2Collection collection = signatureOne.Certificates;

Effective screenshot:

How to get all certificates in a PDF signature

Full code:

using System;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using Spire.Pdf;
using Spire.Pdf.Security;
using Spire.Pdf.Widget;

namespace Get_all_certificates_in_PDF_signature
{
    class Program
    {
        static void Main(string[] args)
        {
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile("UPS.pdf");
            List<PdfSignature> signatures = new List<PdfSignature>();
            var form = (PdfFormWidget)doc.Form;
            for (int i = 0; i < form.FieldsWidget.Count; ++i)
            {
                var field = form.FieldsWidget[i] as PdfSignatureFieldWidget;

                if (field != null && field.Signature != null)
                {
                    PdfSignature signature = field.Signature;
                    signatures.Add(signature);
                }
            }
            PdfSignature signatureOne = signatures[0];
            X509Certificate2Collection collection = signatureOne.Certificates;
            foreach (var certificate in collection)
            {
                Console.WriteLine(certificate.Subject);
            }            
            Console.ReadKey();
        }
    }
}