1PDFDoc doc = new PDFDoc(in_docpath);
2
3Page page1 = doc.GetPage(1);
4
5// Create a digital signature field and associated widget.
6DigitalSignatureField digsig_field = doc.CreateDigitalSignatureField(in_sig_field_name);
7SignatureWidget widgetAnnot = SignatureWidget.Create(doc, new Rect(143, 287, 219, 306), digsig_field);
8page1.AnnotPushBack(widgetAnnot);
9
10// Create a digital signature dictionary inside the digital signature field, in preparation for signing.
11digsig_field.CreateSigDictForCustomSigning("Adobe.PPKLite",
12 in_PAdES_signing_mode? DigitalSignatureField.SubFilterType.e_ETSI_CAdES_detached : 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.
17Date current_date = new Date();
18current_date.SetCurrentTime();
19digsig_field.SetSigDictTimeOfSigning(current_date);
20
21// Save the document incrementally to avoid invalidating any previous signatures.
22doc.Save(in_outpath, SDFDoc.SaveOptions.e_incremental);
23
24// Digest the relevant bytes of the document in accordance with ByteRanges surrounding the signature.
25byte[] pdf_digest = digsig_field.CalculateDigest(DigestAlgorithm.Type.e_sha256);
26
27X509Certificate signer_cert = new X509Certificate(in_cert_path);
28
29/* Optionally, you can add a custom signed attribute at this point, such as one of the PAdES ESS attributes.
30The function we provide takes care of generating the correct PAdES ESS attribute depending on your digest algorithm. */
31byte[] pades_versioned_ess_signing_cert_attribute = digsig_field.GenerateESSSigningCertPAdESAttribute(
32 signer_cert, DigestAlgorithm.Type.e_sha256);
33
34// 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.
35byte[] signedAttrs = DigitalSignatureField.GenerateCMSSignedAttributes(pdf_digest,
36 pades_versioned_ess_signing_cert_attribute);
37
38// Calculate the digest of the signedAttrs (i.e. not the PDF digest, this time).
39byte[] signedAttrs_digest = DigestAlgorithm.CalculateDigest(DigestAlgorithm.Type.e_sha256, signedAttrs);