1const doc = await documentViewer.getDocument().getPDFDoc();
2
3const page1 = await doc.getPage(1);
4
5// Create a digital signature field and associated widget.
6const digsig_field = await doc.createDigitalSignatureField(in_sig_field_name);
7const widgetAnnot = await PDFNet.SignatureWidget.createWithDigitalSignatureField(doc, new PDFNet.Rect(143, 287, 219, 306), digsig_field);
8await page1.annotPushBack(widgetAnnot);
9
10// Create a digital signature dictionary inside the digital signature field, in preparation for signing.
11await digsig_field.createSigDictForCustomSigning("Adobe.PPKLite",
12 in_PAdES_signing_mode? PDFNet.DigitalSignatureField.SubFilterType.e_ETSI_CAdES_detached : PDFNet.DigitalSignatureField.SubFilterType.e_adbe_pkcs7_detached,
13 7500); // For security reasons, set the contents size to a value greater than but as close as possible to the size you expect your final signature to be, in bytes.
14// ... or, if you want to apply a certification signature, use createSigDictForCustomCertification instead.
15
16// (OPTIONAL) Set the signing time in the signature dictionary, if no secure embedded timestamping support is available from your signing provider.
17const current_date = new PDFNet.Date();
18await current_date.setCurrentTime();
19await digsig_field.setSigDictTimeOfSigning(current_date);
20
21await doc.saveMemoryBuffer(PDFNet.SDFDoc.SaveOptions.e_incremental);
22
23// Digest the relevant bytes of the document in accordance with ByteRanges surrounding the signature.
24const pdf_digest = await digsig_field.calculateDigest(PDFNet.DigestAlgorithm.Type.e_SHA256);
25
26const signer_cert = await PDFNet.X509Certificate.createFromBuffer(in_cert_buf);
27
28/* Optionally, you can add a custom signed attribute at this point, such as one of the PAdES ESS attributes.
29The function we provide takes care of generating the correct PAdES ESS attribute depending on your digest algorithm. */
30const pades_versioned_ess_signing_cert_attribute = await PDFNet.DigitalSignatureField.generateESSSigningCertPAdESAttribute(signer_cert, PDFNet.DigestAlgorithm.Type.e_SHA256);
31
32// Generate the signedAttrs component of CMS, passing any optional custom signedAttrs (e.g. PAdES ESS). The signedAttrs are certain attributes that become protected by their inclusion in the signature.
33const signedAttrs = await PDFNet.DigitalSignatureField.generateCMSSignedAttributes(pdf_digest,
34 pades_versioned_ess_signing_cert_attribute);
35const signedAttrsCopy = signedAttrs.slice(); // make a copy for PDFNet.DigitalSignatureField.generateCMSSignature()
36
37// Calculate the digest of the signedAttrs (i.e. not the PDF digest, this time).
38const signedAttrs_digest = await PDFNet.DigestAlgorithm.calculateDigest(PDFNet.DigestAlgorithm.Type.e_SHA256, signedAttrs);