Sign a PDF with a certificate in a browser
Learn to sign a PDF with a digital certificate using JavaScript.
30-second quick start
Sign a PDF document with a digital certificate:
// Replace with your PEM-encoded certificate from your certificate authority.const certificatePem = "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----";
// Replace with your signing service implementation (e.g. HSM, server-side signing, or Web Crypto API).const yourSigningService = { sign: async (data) => { // This typically involves calling your HSM, signing server, or using Web Crypto API. // Implement your signing logic here — return the signature bytes. // This typically involves calling your HSM or signing server, or using Web Crypto API. throw new Error("Implement your signing service"); }};
try { // Sign a PDF with a certificate. await instance.signDocument( { signingData: { signatureType: NutrientViewer.SignatureType.CAdES }, formFieldName: "SignatureField1" // Or `null` to create new field. }, async ({ dataToBeSigned }) => { // Sign the data with your private key (implement your signing logic). const signedData = await yourSigningService.sign(dataToBeSigned); return { signedData, certificates: [certificatePem] }; } ); console.log("Document signed successfully");} catch (error) { console.error("Failed to sign document:", error.message);}For complete implementation details, including certificate setup, timestamping, and long-term validation (LTV), continue reading.
Complete implementation guide
In the add a signature field guide, you learned how to create a signature field. In this section, you’ll sign the field using the certificates you generated when preparing the certificates for signing.
Approval and certification signatures
PDF documents mainly support two types of digital signatures: approval signatures and certification signatures. Approval signatures indicate that a signer agrees with or acknowledges the contents of a document. A single document can contain multiple approval signatures. Meanwhile, certification signatures restrict the kind of changes you can apply to a document once it’s signed. A PDF document supports only one certification signature. Nutrient provides support for approval signatures. For certification signatures, contact the Support team(opens in a new tab).
The remainder of this document will guide you in signing a PDF with an approval signature.
Signing a PDF
To sign a PDF, call the NutrientViewer.Instance#signDocument method. The first argument should be an object instance of SignaturePreparationData, which provides important information about the signature. In this object, you can provide a formFieldName parameter, which should be the fully qualified name of a form field. The signDocument method can create a visible or invisible signature form field and sign it in one step. To do this, set the formFieldName parameter to null or to a form field name that doesn’t exist in the document. To create a visual digital signature, set the position property to the desired position and size of the new signature field. The appearance property configures the appearance of the signed field. It can include the name, date, and signature reason, or a custom company logotype (see how to configure the visual appearance of a digital signature for more information). The flatten property is false by default, but when true, it’ll flatten the document before signing it. Note that flattening a document removes all annotations in the document, including existing digital signatures. If you want to preserve some annotations, like previous digital signatures, use the document editor to flatten the document before calling signDocument (see flattening annotations in PDFs).
The signingData field of type SigningData contains other important information about the digital signature. If you pass more than one certificate in the certificates field, they must form a certificate chain that ends with the signing certificate. We recommend including a certificate chain to a trusted root. The digital signature is then automatically trusted without needing to trust additional certificates (see how to view and validate a digital signature for more information).
By default, the signDocument method creates a CAdES(opens in a new tab) signature if certificates are provided. Otherwise, the method creates a basic digital signature (CMS(opens in a new tab)). You can set the signatureType field of the signingData field of the SignaturePreparationData argument like this:
instance.signDocument({ signingData: { signatureType: NutrientViewer.SignatureType.CAdES } }, ...)If the private key of the signing certificate is available, you can pass it via the privateKey field of SigningData. However, it’s common that production applications store the private key on a protected device (hardware secure module, or HSM), or a separate server. In that case, the second argument of signDocument, described next, is an abstraction of a private key you can use to sign the data.
The second argument of signDocument is a callback. It receives an object with the dataToBeSigned field and an ArrayBuffer of the contents from the document to sign (see NutrientViewer.TwoStepSignatureCallback). This callback function is useful when the private key is “opaque.” An opaque key isn’t directly accessible, because a hardware module on the local computer or a remote server holds it.
In the implementation of this callback function, you should sign dataToBeSigned. You may need to hash the data beforehand, depending on the format the signer expects (consult its documentation for more information). The return value of the callback function depends on the kind of signature produced by the signer.
If the signer produces a plain, raw, PKCS#1 signature format, then NutrientViewer.TwoStepSignatureCallback should return a SignatureCallbackResponseRaw object, with the signed data in the signedData property. You must also return the signing certificate chain corresponding to that signature. Optionally, you can include a timestamp token (see timestamping) as a DER-encoded RFC3161 trusted timestamp. To make the signature LTV enabled, you can also include Online Certificate Status Protocol (OCSP) revocation responses, DER-encoded as described in RFC6960 (see long-term validation).
If the signer produces a signature in PKCS#7/CMS format, then NutrientViewer.TwoStepSignatureCallback should return a SignatureCallbackResponsePkcs7 object, with the signature in the pkcs7 property. Nutrient assumes the PKCS#7 signature may already contain a timestamp.
If any user-side error happens, you must reject the promise to abort the signing process. You’re free to implement this callback in any way you want. Typically, you call a signing service that contains your private key and can sign arbitrary data. If a signing service isn’t available, the following code snippet shows how to implement the callback using the web cryptography(opens in a new tab) browser API:
async function signData({ fileContents, dataToBeSigned }) { try { const privateKeyPromise = fetch("/static/private-key.pem") .then((response) => { if (!response.ok) throw new Error("Failed to fetch private key"); return response.text(); }); const certificatePromise = fetch("/static/certificate.pem") .then((response) => { if (!response.ok) throw new Error("Failed to fetch certificate"); return response.text(); }); const privateKeyPem = await privateKeyPromise; const certificatePem = await certificatePromise;
const signAlgorithm = { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" }, modulusLength: 2048, extractable: false, publicExponent: new Uint8Array([1, 0, 1]) }; const importedPrivateKey = await window.crypto.subtle.importKey( "pkcs8", convertPemToBinary(privateKeyPem), signAlgorithm, true, ["sign"] );
const signedData = await window.crypto.subtle.sign( signAlgorithm, importedPrivateKey, dataToBeSigned );
return { certificates: [certificatePem], signedData }; } catch (error) { console.error("Signing failed:", error.message); throw error; // Re-throw to abort the signing process. }}Note that, for the sake of simplicity, the snippet stores the private key locally in PEM format. This is insecure and shouldn’t be used in production applications. The latest standards for qualified signatures require a secure hardware device to store the private key. To access secure smart cards and hardware security modules (HSMs) using PKCS#11(opens in a new tab), you’ll need to integrate the SDK that the smart card vendor provides. PSPDFKit doesn’t provide direct support for PKCS#11.
Timestamping
Timestamping involves securely maintaining a record of a digital signature. This ensures that, as long as the timestamp’s integrity remains intact, no one, not even the document’s owner, can alter it.
To sign a PDF with a timestamp, you need to provide information about the timestamp authority to the signingData fields’ timestamp property. Providing a valid URL of a timestamp authority is required, while providing a username and password is optional and depends on whether the timestamp authority requires this. The following code snippet shows how to sign a PDF with a timestamp:
instance.signDocument({ signingData: { timestamp: { url: "some url", username: "", password: "" } } }, ...)Because the browser calls the timestamping authority, the timestamping authority must support cross-origin resource sharing (CORS). If the timestamping authority doesn’t support CORS, you can use a proxy server to call the timestamping authority.
Long-term validation (LTV)
LTV is a feature in digital signatures that ensures the longevity of a signature’s validity. This works by incorporating additional information into the signature at the time of signing. This additional information enables any future validator to verify the status of the certificate at the time of signing. This ensures the signature’s validity over an extended period.
LTV information can be added to a signature in two ways:
- By adding LTV information to a signature when it’s created.
- By refreshing or adding LTV information to an existing signature.
Sometimes the person who signs a document doesn’t have access to the internet at the time of signing. In other cases, the recipient of a signed document wants to preserve the document for a long time. In either case, you can create the signature without LTV information and add the LTV information later.
To add LTV information to the signature, the trusted keystore must contain the trust anchor certificate of the signing certificate chain. If the trust anchor certificate isn’t present in the keystore, Nutrient creates the signature without LTV information. To add the trust anchor certificate to the keystore, you need to call the NutrientViewer.Configuration#trustedCAsCallback method.
Adding LTV-enabled signatures
A CAdES signature already requires a certificate chain. To add LTV information when you create a signature, set the ltv property of the signingData field. The following code snippet shows how to add LTV information to a signature when it’s created:
instance.signDocument({ signingData: { ltv: true } }, ...)Refreshing or adding LTV to an existing signature
To refresh or add LTV information to an existing signature, you need to call the NutrientViewer.Instance#setSignaturesLTV method. The method takes an optional array of certificates as an argument. This is a list of certificates needed for long-term validation. It mainly includes signing certificates, along with the timestamp certificate chain, if the signature was timestamped. If the certificate chain isn’t passed, Nutrient searches the document for every signed signature field and tries to extract the signing certificate from it. The following code snippet shows how to refresh or add LTV information to an existing signature:
instance.setSignaturesLTV(certificate);For both use cases, the OCSP responder must support CORS, because the browser calls it. Unfortunately, you can’t use a proxy server to call an OCSP responder that doesn’t support CORS, because the certificate embeds the OCSP responder URL.
Signing a PDF multiple times
One of the prominent features of digital signatures in PDFs is the possibility for an unlimited number of signers. This feature is especially useful for multiparty contracts, legal documents, and other formal agreements where more than two parties are involved. Each of these parties can append their signature to a document, ensuring it carries the approvals needed to make it legally binding.
Each signature you add to a PDF adds an extra layer of security to the document. This increases the integrity of the document up to the point of each signature, a feature known as “non-repudiation.” In simpler terms, non-repudiation ensures that a party involved in a contract or agreement can’t deny the authenticity of their electronic signature. The signature serves as proof of consent or approval.
Each digital signature generates a version, or revision, of the document. Hence, a document can house multiple revisions if you sign it repeatedly with approval signatures (see approval and certification signatures). When third-party software such as Adobe Acrobat verifies a document with several digital signatures, it ensures each revision only includes specific permissible modifications. Typically, new revisions can add notes, fill out form fields, or place subsequent signatures on the document. However, alterations like page modifications invalidate the digital signature.
Here’s a diagram that shows how revisions work in a PDF document.

Digital PDF signatures, which can include timestamps (refer to timestamping for more information), provide an audit trail. It details when each party reviewed and consented to the document’s content. This chronological record is particularly beneficial in compliance scenarios, as it presents an irrefutable timeline of when the parties gave their approvals.
If you wish to sign a document again after making permissible changes (e.g. filling in a form), add a new signature form field by following the steps in the add a signature field section. Then complete the signing process by following the guidelines in the signing a PDF section.
Note that each signature you add slightly increases the file size. This can impact storage and sharing capabilities of the document, especially when you append a large number of signatures. However, given the security that digital signatures provide, this is usually a small price to pay.