Skip to content
DemoSampleAPI ReferenceFAQ

PDF Generation Template Editor

Open-source visual PDF generation engine with customizable templates and developer-friendly APIs.

View on GitHub

Signature Workflow and Validation Reports ​

CPDFSignatureWorkflow provides one-call signing and structured validation. Unlike the "create a signature field, then write the signature" approach in Create Digital Signatures, the workflow creates the field, signs it, and writes the output in a single call, then reloads the output and produces a validation report. The APIs in Create Digital Signatures through Verify Digital Signatures are unchanged and remain available when you need finer control.

Before using the workflow, note that:

  • The workflow reads the file on disk at document.documentURL. Unsaved in-memory changes are not included, so save the document first.
  • Signing always writes to a new output path and never modifies the source file.

The profile property of CPDFSignatureCreateOptions selects the signature type:

ValueDescription
CPDFSignatureProfilePKCS7DetachedThe default. A plain adbe.pkcs7.detached signature with the widest compatibility.
CPDFSignatureProfilePAdESBA PAdES Baseline-B signature (ETSI.CAdES.detached) without a timestamp.
CPDFSignatureProfilePAdESTA PAdES Baseline-T signature: Baseline-B plus an embedded signature timestamp. Requires a TSA.
CPDFSignatureProfileDocumentTimestampA document timestamp (ETSI.RFC3161) that represents no signer identity. Use it with a signing identity created by documentTimestampIdentityWithServerURL: or documentTimestampIdentityWithTSAClient:.

For PAdES Baseline-LT and Baseline-LTA, see PAdES and Long-Term Validation (LTV).

Sign in One Call

The steps to sign with the workflow are as follows:

  1. Specify the PKCS#12 certificate and its password with CPDFSigningIdentity.

  2. Set the signature type, field position, reason, and other information with CPDFSignatureCreateOptions. The appearance uses the same CPDFSignatureConfig as in Create Digital Signatures.

  3. Call signToPath:options: and read the returned CPDFSignatureCreateResult.

verifiesAfterSign defaults to YES: after signing, the workflow reloads the output and produces postSignReport according to postSignValidationOptions. Turn it off for bulk signing when you validate separately. success being YES only means the signed file was written; the post-sign report may still fail, so check postSignReport as well.

This example shows how to create a digital signature with the signature workflow:

swift
// The signing identity: a PKCS#12 certificate and its password.
let identity = CPDFSigningIdentity(pkcs12Path: certificatePath, password: "123")

// Configure the appearance as you would for a visible signature.
let appearance = CPDFSignatureConfig()
appearance.text = "Alan"
appearance.isDrawKey = true
let reasonItem = CPDFSignatureConfigItem()
reasonItem.key = "Reason"
reasonItem.value = "I am the owner of the document."
appearance.contents = [reasonItem]

// Trust anchors for the post-sign validation (a PEM file or an OpenSSL hashed directory).
let postSignChecks = CPDFSignatureValidationOptions()
postSignChecks.trustedCertificatePath = trustedRootsPath

let options = CPDFSignatureCreateOptions()
options.profile = .pAdESB
options.signer = identity
options.fieldName = "Signature1"
options.pageIndex = 0
options.bounds = CGRect(x: 28, y: 420, width: 150, height: 70)
options.reason = "I am the owner of the document."
options.location = "Singapore"
options.appearance = appearance
options.verifiesAfterSign = true
options.postSignValidationOptions = postSignChecks

// The workflow reads the saved file at document.documentURL. All of its methods are synchronous.
DispatchQueue.global(qos: .userInitiated).async {
    let workflow = CPDFSignatureWorkflow(document: document)
    let result = workflow.sign(toPath: signedFilePath, options: options)
    guard result.success else {
        // Signing failed. errors explains why.
        for item in result.errors {
            print("\(item.code): \(item.message)")
        }
        return
    }
    // Signed. postSignReport is the report of the automatic post-sign validation.
    print("Signed \(result.fieldName) with \(result.subFilter), verdict: \(result.postSignReport.overallStatus.rawValue)")
}
objective-c
// The signing identity: a PKCS#12 certificate and its password.
CPDFSigningIdentity *identity = [CPDFSigningIdentity identityWithPKCS12Path:certificatePath password:@"123"];

// Configure the appearance as you would for a visible signature.
CPDFSignatureConfig *appearance = [[CPDFSignatureConfig alloc] init];
appearance.text = @"Alan";
appearance.isDrawKey = YES;
CPDFSignatureConfigItem *reasonItem = [[CPDFSignatureConfigItem alloc] init];
reasonItem.key = @"Reason";
reasonItem.value = @"I am the owner of the document.";
appearance.contents = @[reasonItem];

// Trust anchors for the post-sign validation (a PEM file or an OpenSSL hashed directory).
CPDFSignatureValidationOptions *postSignChecks = [[CPDFSignatureValidationOptions alloc] init];
postSignChecks.trustedCertificatePath = trustedRootsPath;

CPDFSignatureCreateOptions *options = [[CPDFSignatureCreateOptions alloc] init];
options.profile = CPDFSignatureProfilePAdESB;
options.signer = identity;
options.fieldName = @"Signature1";
options.pageIndex = 0;
options.bounds = CGRectMake(28, 420, 150, 70);
options.reason = @"I am the owner of the document.";
options.location = @"Singapore";
options.appearance = appearance;
options.verifiesAfterSign = YES;
options.postSignValidationOptions = postSignChecks;

// The workflow reads the saved file at document.documentURL. All of its methods are synchronous.
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
    CPDFSignatureWorkflow *workflow = [[CPDFSignatureWorkflow alloc] initWithDocument:document];
    CPDFSignatureCreateResult *result = [workflow signToPath:signedFilePath options:options];
    if (!result.success) {
        // Signing failed. errors explains why.
        for (CPDFValidationReportItem *item in result.errors) {
            NSLog(@"%@: %@", item.code, item.message);
        }
        return;
    }
    // Signed. postSignReport is the report of the automatic post-sign validation.
    NSLog(@"Signed %@ with %@, verdict: %ld", result.fieldName, result.subFilter, (long)result.postSignReport.overallStatus);
});

Note: The workflow appearance supports text and image content. Ink paths, font size, and rotation are not available through appearance; when you need them, use the CPDFSignatureWidgetAnnotation approach in Create Digital Signatures. The signature workflow does not create certification (DocMDP) signatures and does not lock form fields after signing.

Validate the Signatures in a Document

validateDocumentWithOptions: validates every signature in an open document (set fieldName of CPDFSignatureWorkflowValidationOptions to validate a single signature). validatePath:options: validates a PDF file on disk without opening it. The result contains one CPDFSignatureValidationReport per signature, and each report lists CPDFValidationReportItem checks by category (category), status (status), and severity (severity: CPDFValidationSeverityInfo, CPDFValidationSeverityWarning, CPDFValidationSeverityError).

Use CPDFSignatureValidationOptions to choose the checks and the trust material:

  • trustedCertificatePath: the trust anchors, either a PEM bundle file or an OpenSSL hashed directory. The SDK ships no trust anchors. Without them, the certificate chain verdict (including the TSA chain of timestamps) is CPDFValidationStatusIndeterminate rather than CPDFValidationStatusValid. This path is independent of the trusted certificate folder in Trust Certificate: certificates trusted with addToTrustedCertificates do not take part in this chain validation, and the trusted certificate folder cannot be passed in as this path.
  • checksRevocation: whether to check OCSP / CRL revocation status. Defaults to NO. When on, validation may go online.
  • validationTimeEpochSeconds: the validation time in Unix epoch seconds. Defaults to 0, which uses the trusted timestamp time, then the signing time, then the current time.
  • checksIntegrity, checksCoverage, checksDocumentPermissions, checksCertificateChain, checksTimestamp: enable the integrity, ByteRange coverage, document permission, certificate chain, and timestamp checks. All default to YES.

This example shows how to validate the digital signatures in a document:

swift
let validationOptions = CPDFSignatureValidationOptions()
// The SDK ships no trust anchors. Without them, the chain verdict is Indeterminate.
validationOptions.trustedCertificatePath = Bundle.main.path(forResource: "trusted_roots", ofType: "pem")
// Revocation checking is off by default. When on, validation may fetch OCSP / CRL over the network.
validationOptions.checksRevocation = false

let workflowOptions = CPDFSignatureWorkflowValidationOptions()
workflowOptions.validationOptions = validationOptions

DispatchQueue.global(qos: .userInitiated).async {
    let workflow = CPDFSignatureWorkflow(document: document)
    let result = workflow.validateDocument(with: workflowOptions)

    // One report per signature.
    for report in result.reports {
        switch report.overallStatus {
        case .valid:
            print("\(report.fieldName): valid")
        case .invalid:
            print("\(report.fieldName): invalid")
        case .indeterminate:
            print("\(report.fieldName): indeterminate")
        default:
            print("\(report.fieldName): not checked")
        }

        // Read by severity: list the errors only.
        for item in report.items(with: .error) {
            print("  [error] \(item.code): \(item.message)")
        }

        // Read by category: for example, the certificate chain results.
        for item in report.items where item.category == .certificateChain {
            print("  [chain] status \(item.status.rawValue): \(item.message)")
        }
    }
}
objective-c
CPDFSignatureValidationOptions *validationOptions = [[CPDFSignatureValidationOptions alloc] init];
// The SDK ships no trust anchors. Without them, the chain verdict is Indeterminate.
validationOptions.trustedCertificatePath = [[NSBundle mainBundle] pathForResource:@"trusted_roots" ofType:@"pem"];
// Revocation checking is off by default. When on, validation may fetch OCSP / CRL over the network.
validationOptions.checksRevocation = NO;

CPDFSignatureWorkflowValidationOptions *workflowOptions = [[CPDFSignatureWorkflowValidationOptions alloc] init];
workflowOptions.validationOptions = validationOptions;

dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
    CPDFSignatureWorkflow *workflow = [[CPDFSignatureWorkflow alloc] initWithDocument:document];
    CPDFSignatureWorkflowValidationResult *result = [workflow validateDocumentWithOptions:workflowOptions];

    // One report per signature.
    for (CPDFSignatureValidationReport *report in result.reports) {
        switch (report.overallStatus) {
            case CPDFValidationStatusValid:
                NSLog(@"%@: valid", report.fieldName);
                break;
            case CPDFValidationStatusInvalid:
                NSLog(@"%@: invalid", report.fieldName);
                break;
            case CPDFValidationStatusIndeterminate:
                NSLog(@"%@: indeterminate", report.fieldName);
                break;
            default:
                NSLog(@"%@: not checked", report.fieldName);
                break;
        }

        // Read by severity: list the errors only.
        for (CPDFValidationReportItem *item in [report itemsWithSeverity:CPDFValidationSeverityError]) {
            NSLog(@"  [error] %@: %@", item.code, item.message);
        }

        // Read by category: for example, the certificate chain results.
        for (CPDFValidationReportItem *item in report.items) {
            if (item.category == CPDFValidationCategoryCertificateChain) {
                NSLog(@"  [chain] status %ld: %@", (long)item.status, item.message);
            }
        }
    }
});

The values of CPDFValidationStatus are as follows:

ValueDescription
CPDFValidationStatusValidThe check passed.
CPDFValidationStatusInvalidThe check failed.
CPDFValidationStatusIndeterminateThe check ran but could not reach a verdict, for example a chain that does not lead to a known trust anchor.
CPDFValidationStatusNotCheckedThe check did not run: it was disabled, or its input was unavailable (for example, revocation data while offline). Not a failure.

The values of CPDFValidationCategory are as follows:

ValueDescription
CPDFValidationCategorySignatureIntegrityCryptographic integrity of the PKCS#7 / CMS signature.
CPDFValidationCategoryByteRangeCoverageWhether the ByteRange covers what it claims.
CPDFValidationCategoryDocumentRevisionThe document revision the signature signs.
CPDFValidationCategoryDocumentPermissionsDocMDP / document permission state.
CPDFValidationCategoryCertificateChainCertificate chain building and trust.
CPDFValidationCategoryRevocationOCSP / CRL revocation status.
CPDFValidationCategoryTimestampEmbedded and document timestamps.
CPDFValidationCategoryAlgorithmPolicyAlgorithm policy (weak digests, key sizes, etc.).
CPDFValidationCategoryPadesProfilePAdES baseline level.
CPDFValidationCategorySignatureAppearanceSignature appearance.
CPDFValidationCategoryInputThe input file or parameters.

Note: success of CPDFSignatureWorkflowValidationResult is YES only when overallStatus is CPDFValidationStatusValid. NO does not mean that validation did not run, nor that the signature is broken: an untrusted TSA chain or missing long-term validation material also produces NO. Read overallStatus and the reports to tell these cases apart. Match on the item code (for example timestamp.embedded.imprint.mismatch) in your logic; message is for display only and is not localized.

Configure the Algorithm Policy

CPDFSignatureAlgorithmPolicy defines what happens when a weak algorithm is found (CPDFWeakAlgorithmActionAllow, CPDFWeakAlgorithmActionWarn, CPDFWeakAlgorithmActionReject). By default, SHA-1 produces a warning, MD5 is rejected, and RSA keys must be at least 2048 bits. When signing, set the policy on algorithmPolicy of CPDFSignatureCreateOptions; the post-sign validation automatically uses the same policy (overwriting the one in postSignValidationOptions). For standalone validation, set it on algorithmPolicy of CPDFSignatureValidationOptions. Policy violations are reported under the CPDFValidationCategoryAlgorithmPolicy category.

This example shows how to validate signatures with a custom algorithm policy:

swift
let policy = CPDFSignatureAlgorithmPolicy()
policy.sha1Action = .reject         // Default: warn
policy.md5Action = .reject          // Default: reject
policy.minimumRSAKeyBits = 3072     // Default: 2048

let validationOptions = CPDFSignatureValidationOptions()
validationOptions.algorithmPolicy = policy

let workflowOptions = CPDFSignatureWorkflowValidationOptions()
workflowOptions.validationOptions = validationOptions

DispatchQueue.global(qos: .userInitiated).async {
    // Validating a file on disk needs no open document.
    let result = CPDFSignatureWorkflow().validatePath(signedFilePath, options: workflowOptions)
    for report in result.reports {
        for item in report.items where item.category == .algorithmPolicy {
            print("\(report.fieldName) \(item.code): \(item.message)")
        }
    }
}
objective-c
CPDFSignatureAlgorithmPolicy *policy = [[CPDFSignatureAlgorithmPolicy alloc] init];
policy.sha1Action = CPDFWeakAlgorithmActionReject;   // Default: Warn
policy.md5Action = CPDFWeakAlgorithmActionReject;    // Default: Reject
policy.minimumRSAKeyBits = 3072;                     // Default: 2048

CPDFSignatureValidationOptions *validationOptions = [[CPDFSignatureValidationOptions alloc] init];
validationOptions.algorithmPolicy = policy;

CPDFSignatureWorkflowValidationOptions *workflowOptions = [[CPDFSignatureWorkflowValidationOptions alloc] init];
workflowOptions.validationOptions = validationOptions;

dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
    // Validating a file on disk needs no open document.
    CPDFSignatureWorkflow *workflow = [[CPDFSignatureWorkflow alloc] init];
    CPDFSignatureWorkflowValidationResult *result = [workflow validatePath:signedFilePath options:workflowOptions];
    for (CPDFSignatureValidationReport *report in result.reports) {
        for (CPDFValidationReportItem *item in report.items) {
            if (item.category == CPDFValidationCategoryAlgorithmPolicy) {
                NSLog(@"%@ %@: %@", report.fieldName, item.code, item.message);
            }
        }
    }
});