PDF Generation Template Editor
Open-source visual PDF generation engine with customizable templates and developer-friendly APIs.
Open-source visual PDF generation engine with customizable templates and developer-friendly APIs.
PAdES (PDF Advanced Electronic Signatures, ETSI EN 319 142) is the PDF advanced electronic signature format recognized by the EU eIDAS regulation. CPDFPadesSigner produces signatures at the following four baseline levels, each containing everything in the level before it:
| Level | Description | Output files |
|---|---|---|
CPDFPadesBaselineProfileB | A basic signature that references the signing certificate. | signedPath |
CPDFPadesBaselineProfileT | Baseline-B plus a trusted signature timestamp. Requires a TSA. | signedPath |
CPDFPadesBaselineProfileLT | Baseline-T plus the certificate chain and OCSP / CRL revocation data written to DSS / VRI, so the signature still verifies after the certificate expires. | signedPath, ltvPath |
CPDFPadesBaselineProfileLTA | Baseline-LT plus a document timestamp covering the long-term validation material, which can be renewed periodically. | signedPath, ltvPath, ltaPath |
Each level writes its own file, and no two paths may be the same. The final document is the last file written (ltaPath for LTA, ltvPath for LT, signedPath otherwise). The earlier files are intermediate states that you can keep as an audit trail or delete.
Note: Instances of CPDFPadesSigner and CPDFLtvService own core-library state. Use each instance from one thread only, even when working on different documents.
Create PAdES-B / PAdES-T Signatures
signatureOptions of CPDFPadesCreateOptions describes the inner signature (signing identity, field, appearance, and so on). Its profile is set from the baseline level for you, so leave it alone. For level T and above, the signature timestamp comes from tsaClient of signatureOptions.
In the returned CPDFPadesCreateResult, signatureResult.success means the signature was written, and a signatureResult.subFilter of ETSI.CAdES.detached means a PAdES signature was produced. success means the requested level was reached in full.
This example shows how to create a PAdES-T signature:
let tsaClient = CPDFURLSessionTSAClient(url: URL(string: "https://tsa.example.com/tsr")!)
// The inner signature: signing identity, signature field, and signature timestamp.
let signatureOptions = CPDFSignatureCreateOptions()
signatureOptions.signer = CPDFSigningIdentity(pkcs12Path: certificatePath, password: "123")
signatureOptions.tsaClient = tsaClient
signatureOptions.fieldName = "Signature1"
signatureOptions.pageIndex = 0
signatureOptions.bounds = CGRect(x: 28, y: 420, width: 150, height: 70)
let padesOptions = CPDFPadesCreateOptions()
padesOptions.profile = .T
padesOptions.signatureOptions = signatureOptions
padesOptions.trustedCertPath = trustedRootsPath
DispatchQueue.global(qos: .userInitiated).async {
let signer = CPDFPadesSigner(document: document)
let result = signer.sign(toPath: signedPath, ltvPath: nil, ltaPath: nil, options: padesOptions)
if result.signatureResult.success {
// ETSI.CAdES.detached means a PAdES signature was written.
print("Signed: \(result.signedPath), subFilter: \(result.signatureResult.subFilter)")
}
for item in result.errors {
print("\(item.code): \(item.message)")
}
}CPDFURLSessionTSAClient *tsaClient = [[CPDFURLSessionTSAClient alloc] initWithURL:[NSURL URLWithString:@"https://tsa.example.com/tsr"]];
// The inner signature: signing identity, signature field, and signature timestamp.
CPDFSignatureCreateOptions *signatureOptions = [[CPDFSignatureCreateOptions alloc] init];
signatureOptions.signer = [CPDFSigningIdentity identityWithPKCS12Path:certificatePath password:@"123"];
signatureOptions.tsaClient = tsaClient;
signatureOptions.fieldName = @"Signature1";
signatureOptions.pageIndex = 0;
signatureOptions.bounds = CGRectMake(28, 420, 150, 70);
CPDFPadesCreateOptions *padesOptions = [[CPDFPadesCreateOptions alloc] init];
padesOptions.profile = CPDFPadesBaselineProfileT;
padesOptions.signatureOptions = signatureOptions;
padesOptions.trustedCertPath = trustedRootsPath;
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
CPDFPadesSigner *signer = [[CPDFPadesSigner alloc] initWithDocument:document];
CPDFPadesCreateResult *result = [signer signToPath:signedPath ltvPath:nil ltaPath:nil options:padesOptions];
if (result.signatureResult.success) {
// ETSI.CAdES.detached means a PAdES signature was written.
NSLog(@"Signed: %@, subFilter: %@", result.signedPath, result.signatureResult.subFilter);
}
for (CPDFValidationReportItem *item in result.errors) {
NSLog(@"%@: %@", item.code, item.message);
}
});Add Long-Term Validation Material on iOS (LT / LTA)
LT and LTA need the signing certificate chain and OCSP / CRL revocation data. autoCollectLTVValidationInfo of CPDFPadesCreateOptions defaults to YES, in which case the core library downloads revocation data with its own synchronous HTTP client. That client does not use NSURLSession, so ATS, the system proxy, and timeouts do not apply. On iOS, collect the revocation data in your app and pass it in through ltvOptions instead:
Create a PAdES-T signature with CPDFPadesSigner (see above).
Build the signing certificate chain locally with CPDFCertificateChainBuilder, and read the OCSP / CRL addresses from the certificate with discoverSourcesInCertificateDER: of CPDFRevocationService.
Download the CRL or OCSP response with your own NSURLSession code, then validate it locally with validateCRL: or validateOCSPResponse: of CPDFRevocationService. These two methods never go online.
Put the chain and the revocation data into CPDFLtvValidationInfo and call prolongLTVFromPath:ltvPath:ltaPath:options: to write DSS / VRI. When appendDocumentTimestamp is YES, a document timestamp is appended as well, producing an LTA document.
signatureContentsDER of CPDFLtvValidationInfo must be the complete raw bytes of the signature /Contents, including the reserved padding, not the trimmed CMS container. Otherwise the VRI entry is written under a key the validator never looks up. Obtain these bytes with rawSignatureContentsForSignature:atPath: of CPDFSignatureCoverageChecker.
This example shows how to add long-term validation material and a document timestamp on iOS (using a CRL):
let tsaClient = CPDFURLSessionTSAClient(url: URL(string: "https://tsa.example.com/tsr")!)
DispatchQueue.global(qos: .userInitiated).async {
// 1. Read the signature and its certificates from the signed file (the signer certificate is the last element).
guard let signedDocument = CPDFDocument(url: URL(fileURLWithPath: signedPath)),
let signature = signedDocument.signatures()?.first,
let certificates = signature.signers?.first?.certificates,
let leafDER = certificates.last?.derData() else { return }
// 2. Build the certificate chain locally (no network). The chain is ordered leaf first.
let store = CPDFCertificateStore()
store.trustedCertificatePath = trustedRootsPath
for certificate in certificates.dropLast() {
if let der = certificate.derData() {
store.addIntermediateCertificateDER(der)
}
}
let chain = CPDFCertificateChainBuilder().buildChain(forCertificateDER: leafDER, store: store, allowPartialChain: true)
guard chain.success, chain.chainDER.count >= 2 else { return }
// 3. Read the CRL distribution points, download the CRL with your own URLSession code, then validate it locally.
let revocation = CPDFRevocationService()
let sources = revocation.discoverSources(inCertificateDER: leafDER)
guard let crlURL = sources.crlURLs.first.flatMap({ URL(string: $0) }),
let crlData = downloadData(from: crlURL) else { return }
let input = CPDFRevocationCheckInput()
input.subjectCertificateDER = leafDER
input.issuerCertificateDER = chain.chainDER[1]
input.crlDER = crlData
let check = revocation.validateCRL(input)
guard check.success, check.status == .good else { return }
// 4. Assemble the LTV material. The signature /Contents must be the raw bytes, padding included.
let info = CPDFLtvValidationInfo()
info.signatureContentsDER = CPDFSignatureCoverageChecker().rawSignatureContents(for: signature, atPath: signedPath)
info.certificatesDER = chain.chainDER
info.crlsDER = [crlData]
let ltvOptions = CPDFLtvAddOptions()
ltvOptions.validationInfo = [info]
// 5. Write DSS / VRI (LT) and append a document timestamp (LTA).
let prolongOptions = CPDFPadesProlongOptions()
prolongOptions.ltvOptions = ltvOptions
prolongOptions.autoCollectLTVValidationInfo = false
prolongOptions.appendDocumentTimestamp = true
prolongOptions.ltaTSAClient = tsaClient
prolongOptions.trustedCertPath = trustedRootsPath
let result = CPDFPadesSigner().prolongLTV(fromPath: signedPath, ltvPath: ltvPath, ltaPath: ltaPath, options: prolongOptions)
print("LTV written: \(result.ltvResult.success), LTA file: \(result.ltaPath)")
}CPDFURLSessionTSAClient *tsaClient = [[CPDFURLSessionTSAClient alloc] initWithURL:[NSURL URLWithString:@"https://tsa.example.com/tsr"]];
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
// 1. Read the signature and its certificates from the signed file (the signer certificate is the last element).
CPDFDocument *signedDocument = [[CPDFDocument alloc] initWithURL:[NSURL fileURLWithPath:signedPath]];
CPDFSignature *signature = [signedDocument signatures].firstObject;
NSArray<CPDFSignatureCertificate *> *certificates = signature.signers.firstObject.certificates;
NSData *leafDER = [certificates.lastObject DERData];
if (!leafDER) {
return;
}
// 2. Build the certificate chain locally (no network). The chain is ordered leaf first.
CPDFCertificateStore *store = [[CPDFCertificateStore alloc] init];
store.trustedCertificatePath = trustedRootsPath;
for (NSUInteger i = 0; i + 1 < certificates.count; i++) {
NSData *der = [certificates[i] DERData];
if (der) {
[store addIntermediateCertificateDER:der];
}
}
CPDFCertificateChainBuildResult *chain = [[[CPDFCertificateChainBuilder alloc] init] buildChainForCertificateDER:leafDER store:store allowPartialChain:YES];
if (!chain.success || chain.chainDER.count < 2) {
return;
}
// 3. Read the CRL distribution points, download the CRL with your own URLSession code, then validate it locally.
CPDFRevocationService *revocation = [[CPDFRevocationService alloc] init];
CPDFRevocationSources *sources = [revocation discoverSourcesInCertificateDER:leafDER];
NSString *crlURLString = sources.crlURLs.firstObject;
NSData *crlData = crlURLString ? downloadData([NSURL URLWithString:crlURLString]) : nil;
if (!crlData) {
return;
}
CPDFRevocationCheckInput *input = [[CPDFRevocationCheckInput alloc] init];
input.subjectCertificateDER = leafDER;
input.issuerCertificateDER = chain.chainDER[1];
input.crlDER = crlData;
CPDFRevocationCheckResult *check = [revocation validateCRL:input];
if (!check.success || check.status != CPDFRevocationStatusGood) {
return;
}
// 4. Assemble the LTV material. The signature /Contents must be the raw bytes, padding included.
CPDFLtvValidationInfo *info = [[CPDFLtvValidationInfo alloc] init];
info.signatureContentsDER = [[[CPDFSignatureCoverageChecker alloc] init] rawSignatureContentsForSignature:signature atPath:signedPath];
info.certificatesDER = chain.chainDER;
info.crlsDER = @[crlData];
CPDFLtvAddOptions *ltvOptions = [[CPDFLtvAddOptions alloc] init];
ltvOptions.validationInfo = @[info];
// 5. Write DSS / VRI (LT) and append a document timestamp (LTA).
CPDFPadesProlongOptions *prolongOptions = [[CPDFPadesProlongOptions alloc] init];
prolongOptions.ltvOptions = ltvOptions;
prolongOptions.autoCollectLTVValidationInfo = NO;
prolongOptions.appendDocumentTimestamp = YES;
prolongOptions.ltaTSAClient = tsaClient;
prolongOptions.trustedCertPath = trustedRootsPath;
CPDFPadesSigner *signer = [[CPDFPadesSigner alloc] init];
CPDFPadesProlongResult *result = [signer prolongLTVFromPath:signedPath ltvPath:ltvPath ltaPath:ltaPath options:prolongOptions];
NSLog(@"LTV written: %d, LTA file: %@", result.ltvResult.success, result.ltaPath);
});If your use case allows the core library to go online directly, you can instead set profile to CPDFPadesBaselineProfileLT or CPDFPadesBaselineProfileLTA, pass ltvPath and ltaPath, set ltaTSAClient, and let signToPath:ltvPath:ltaPath:options: sign and collect the long-term validation material in one call.
Note: fetchOCSPResponse:, fetchCRL:, and fetchAndValidateBestAvailable: of CPDFRevocationService also make blocking network requests from the core library through OpenSSL, bypassing ATS and the system proxy. They are not recommended on iOS.
Renew Archived Documents
prolongLTVFromPath:ltvPath:ltaPath:options: also renews archived signed documents: before the existing revocation data or document timestamp certificate expires, fetch current revocation data and append a new document timestamp. The method needs no open document and also works on PDFs signed by other software. Note that every append embeds the certificates and CRLs already in the DSS again, so the file grows each time.
Check the LTV Status of a Document
CPDFLtvService only reads the DSS / VRI in a document and never goes online. inspectDSSInDocument: summarizes the DSS contents. assessReadinessOfDocument: judges whether every signature in the document has complete long-term validation material; when it does not, missingMaterials lists what is missing, which tells you whether to fetch fresh revocation data or re-sign.
This example shows how to check the LTV status of a document:
DispatchQueue.global(qos: .utility).async {
guard let document = CPDFDocument(url: URL(fileURLWithPath: ltaPath)) else { return }
// CPDFLtvService only reads document structure and never goes online. Use one instance per thread.
let service = CPDFLtvService()
let dss = service.inspectDSS(in: document)
if dss.success {
print("DSS: \(dss.dssInfo.hasDSS), VRI entries: \(dss.dssInfo.vriEntriesCount), CRLs: \(dss.dssInfo.crlsCount)")
}
let readiness = service.assessReadiness(of: document)
if readiness.success {
let info = readiness.readinessInfo
print("LTV ready: \(info.ltvReady), hint: \(info.profileHint)")
// When not ready, missingMaterials names what is missing.
for missing in info.missingMaterials {
print("Missing: \(missing)")
}
}
}dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{
CPDFDocument *document = [[CPDFDocument alloc] initWithURL:[NSURL fileURLWithPath:ltaPath]];
// CPDFLtvService only reads document structure and never goes online. Use one instance per thread.
CPDFLtvService *service = [[CPDFLtvService alloc] init];
CPDFLtvInspectResult *dss = [service inspectDSSInDocument:document];
if (dss.success) {
NSLog(@"DSS: %d, VRI entries: %ld, CRLs: %ld", dss.dssInfo.hasDSS, (long)dss.dssInfo.vriEntriesCount, (long)dss.dssInfo.crlsCount);
}
CPDFLtvReadinessResult *readiness = [service assessReadinessOfDocument:document];
if (readiness.success) {
CPDFLtvReadinessInfo *info = readiness.readinessInfo;
NSLog(@"LTV ready: %d, hint: %@", info.ltvReady, info.profileHint);
// When not ready, missingMaterials names what is missing.
for (NSString *missing in info.missingMaterials) {
NSLog(@"Missing: %@", missing);
}
}
});