C# and Java Code to Digitally Sign PDF Files With a Certificate

In the “Secure PDF Files With a Password in C#, VB, and Java” article, we described how to use the PDFFile class from the PDF SDK to password protect and encrypt PDF files. Using the PDFFile class also makes digitally signing PDF files just as easy! The PDFFile class is available for .NET FX, .NET Core, and Java.

Digitally signing PDF files provides assurance to users that they are seeing an unmodified version of the PDF. Any change to the PDF content will invalidate the digital signature and alert the user that something has changed.

Below are some C# and Java code snippets that digitally sign PDF files with the PDFFile class. Be sure to check out the tutorials in our documentation as well.

Digitally Sign PDF Files – C# Code


private static void Main()
{
   if (SetLicense() == false)
   {
      Console.WriteLine("Bad LEADTOOLS license or license not set.");
      return;
   }
   if (CheckDigitalSignatureSupportStatus() == false)
   {
      Console.WriteLine("Digital Signature functionality is not available. "
                        + "Make sure you have the Open SSL libs: "
                        + "https://www.leadtools.com/help/sdk/v22/dh/to/lead-compiled-openssl-binaries.html");
      return;
   }

   SignPdf();
}

private static void SignPdf()
{
   const string  password = "password1234";
   var pdfFile = new Leadtools.Pdf.PDFFile(LeadtoolsInstallPath + "\\Resources\\Images\\pdf\\sign\\input.pdf");
   pdfFile.SignDocument(LeadtoolsInstallPath + "\\Resources\\Images\\pdf\\sign\\signed.pdf",
                        LeadtoolsInstallPath + "\\Resources\\Images\\pdf\\sign\\pdf.pfx",
                        password);
}

public static bool SetLicense()
{
   if (!RasterSupport.KernelExpired) return !RasterSupport.KernelExpired;
   try
   {
      var licString = File.ReadAllText(Program.LeadtoolsLicensePath);
      var developerKey = File.ReadAllText(Program.LeadtoolsLicensePath + ".key");
      var licBytes = System.Text.Encoding.UTF8.GetBytes(licString);
      RasterSupport.SetLicense(licBytes, developerKey);
   }
   catch (Exception ex)
   {
      Console.WriteLine(ex.Message);
   }
   return !RasterSupport.KernelExpired;
}

public static bool CheckDigitalSignatureSupportStatus()
{
   SetOpenSslBinFolder();
   // https://www.leadtools.com/help/sdk/v22/dh/pdf/pdfdocument-getdigitalsignaturesupportstatus.html
   return PDFDocument.GetDigitalSignatureSupportStatus() == RasterExceptionCode.Success;
}

public static void SetOpenSslBinFolder()
{
   RasterDefaults.SetResourceDirectory(LEADResourceDirectory.OpenSSL, LeadtoolsInstallPath + "\\Bin\\CDLL\\x64");
}

Digitally Sign PDF Files – Java Code


public static void main(String[] args) throws Exception {
    LoadLibs();
    if(SetLicense() == false){
        System.out.println("Bad LEADTOOLS license or license not set.");
        return;
    }
    if(CheckDigitalSignatureSupportStatus() == false){
        System.out.println(
           "Digital Signature functionality is not available. "
           + "Make sure you have the Open SSL libs: "
           + "https://www.leadtools.com/help/sdk/v22/dh/to/lead-compiled-openssl-binaries.html");
        return;
    }
    SignPdf();
}
    
private static void SignPdf() {
    final String password = "password1234";
    final PDFFile pdfFile = new PDFFile(LEADTOOLSINSTALLPATH + "\\Resources\\Images\\pdf\\sign\\input.pdf");
    pdfFile.signDocument(LEADTOOLSINSTALLPATH + "\\Resources\\Images\\pdf\\sign\\signed.pdf",
                            LEADTOOLSINSTALLPATH + "\\Resources\\Images\\pdf\\sign\\pdf.pfx",
                            password);
}

public static Boolean CheckDigitalSignatureSupportStatus() {
    // https://www.leadtools.com/help/sdk/v22/dh/pdf/pdfdocument-getdigitalsignaturesupportstatus.html
    return PDFDocument.getDigitalSignatureSupportStatus() == RasterExceptionCode.SUCCESS;
}
private static void LoadLibs() {
    Platform.setLibPath(LEADTOOLSINSTALLPATH + "\\Bin\\CDLL\\x64");
    Platform.loadLibrary(LTLibrary.LEADTOOLS);
    Platform.loadLibrary(LTLibrary.PDF);
}
private static boolean SetLicense() {
    if (!RasterSupport.getKernelExpired()) return !RasterSupport.getKernelExpired();
    try {
        final String licensePathString = LEADTOOLSINSTALLPATH + "\\Support\\Common\\License\\LEADTOOLS.lic";
        final String licenseKeyPathString = licensePathString + ".key";
        RasterSupport.setLicense(licensePathString, Files.readString(Path.of(licenseKeyPathString)));
    }
    catch (Exception ex) {
        System.out.println(ex.getMessage());
    }
    return !RasterSupport.getKernelExpired();
}

Create Self-signed Certificate in PowerShell

To create a proof of concept, you can quickly generate a self-signed certificate to use for testing. Below is the PowerShell script that I used. This script requires that you run PowerShell with elevated permissions.


$myName = "Your Name"
$myEmail = "your@emaildomain.tld"
$certPassword = "password1234"

$cert = New-SelfSignedCertificate -Type Custom -certstorelocation cert:\localmachine\my -Container test* -Subject "CN=$myName" -TextExtension @("2.5.29.37={text}1.3.6.1.5.5.7.3.2","2.5.29.17={text}upn=$myEmail") -KeyUsage DigitalSignature -KeyAlgorithm RSA -KeyLength 2048 -NotAfter (Get-Date).AddMonths(6)

$pwd = ConvertTo-SecureString -String "$certPassword" -Force -AsPlainText
$path = "cert:\localMachine\my\" + $cert.thumbprint

Export-PfxCertificate -cert $path -FilePath c:\temp\pdf\pdf.pfx -Password $pwd

See For Yourself – Free Evaluation

Download the LEADTOOLS SDK for free. It’s fully-functional for 60 days and comes with free chat and email support.

Stay Tuned For More Conversion Samples

Did you see our previous post, “Convert HTML to PDF in C#, VB, and Java”? Stay tuned for more PDF examples to see how LEADTOOLS easily fits into any workflow involving PDF files. Need help in the meantime? Contact our support team for free technical support! For pricing or licensing questions, you can contact our sales team via email or call us at +1-704-332-5532.

About 

Developer Advocate

    Find more about me on:
  • linkedin
  • twitter
  • youtube
This entry was posted in PDF and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *