Sign with PKCS12 File

This guide explains the process of digitally signing a PDF file using a PKCS12 (.p12/.pfx) file.

Before you begin

You should get your API key from your UniCloud account.

If this is your first time using UniPDF SDK, follow this guide to set up a local development environment.

Project setup

Clone the project repository

In your terminal, clone the examples repository using the following command: It contains the Go code we will be using for this guide.

git clone https://github.com/unidoc/unipdf-examples.git

Then navigate to the signatures folder in the unipdf-examples directory.

cd unipdf-examples/signatures

Configure environment variables

Configure your license key using the following command: Replace the UNIDOC_LICENSE_API_KEY with your API credentials from your UniCloud account.

Linux/Mac

export UNIDOC_LICENSE_API_KEY=PUT_YOUR_API_KEY_HERE

Windows

set UNIDOC_LICENSE_API_KEY=PUT_YOUR_API_KEY_HERE

How it works

In the example code, the import section imports the necessary UniPDF packages and other Go libraries. The init function loads the metered license key from the system environment and authenticates the library request.

The main function defined in lines 37-128, contains all the code used to sign a PDF file using PKCS12. Let us try to see how this is done by following the code in this function. In line 39-42, the number of command-line arguments is checked. If this check passes then the necessary inputs are obtained from the command line arguments as follows:

p12Path := args[1]
password := args[2]
inputPath := args[3]
outputPath := args[4]

The private key and X509 certificate are obtained from the P12 file using pkcs12.Decode function. In line 72, a new PdfAppender is created from the PdfReader using model.NewPdfAppender(reader). The signature handler, which is later used to create the signature is created in line 78. Then a PdfSignature is created using model.NewPdfSignature(handler) in line 84. Following this, the signature is initialized by calling signature.Initialize() method in line 89.

A model.PdfFieldSignature is created using the following piece of code:

opts := annotator.NewSignatureFieldOpts()
opts.FontSize = 10
opts.Rect = []float64{10, 25, 75, 60}

field, err := annotator.NewSignatureField(
  signature,
  []*annotator.SignatureLine{
    annotator.NewSignatureLine("Name", "John Doe"),
    annotator.NewSignatureLine("Date", "2019.16.04"),
    annotator.NewSignatureLine("Reason", "External signature test"),
  },
  opts,
)
field.T = core.MakeString("Self signed PDF")

In line 109, the document is signed using appender.Sign(1, field). Finally, the document is written to a file at outputPath provided in the command line arguments.

Run the code

Run the code using the following command:

go run pdf_sign_pkcs12.go <FILE.p12> <PASSWORD> <INPUT_PDF_PATH> <OUTPUT_PDF_PATH>

Got any Questions?

We're here to help you.