Pdf React Native Reference Documentation

Pdf

Current Version: 11.6.1

PDF Signing, Metadata, and Attachments

Work with PDF signatures, embedded files, metadata, and LTV information

Chilkat.Pdf provides PDF operations focused on digital signatures, embedded files, metadata, signature verification, and long-term validation support. It can load PDFs from files or memory, inspect page, signature, and attachment counts, sign PDFs with visible or invisible signatures, verify existing signatures, retrieve signer certificates, and manage DSS/LTV verification information.

Digital signatures Sign, certify, countersign, timestamp, and verify PDF signatures.
Embedded files Add attachments to PDFs or extract existing embedded files.
Metadata Read, update, or insert XMP metadata in an existing PDF.
LTV and DSS Inspect or add certificates, OCSP responses, and CRL information.

The class is commonly used for PDF signing workflows, PDF/A-3-style embedded-file scenarios, signature validation, and adding long-term validation material after signing.

Object Creation

// npm install @chilkat/react-native react-native-nitro-modules
// (React Native 0.76+ with the New Architecture; then `pod install` for iOS.  The Chilkat
//  native library is downloaded and verified during the native build -- see the package README.)

import { Chilkat, Pdf } from '@chilkat/react-native'

// Once per app start, before any other Chilkat call:
Chilkat.unlockBundle('Anything for 30-day trial')   // shorthand for new Global().unlockBundle(..)

const pdf = new Pdf()
// ... the native object is released when `pdf` is garbage collected, or now with pdf.dispose()
new Pdf()

Creates the underlying native Chilkat object. Pdf is a Nitro Module HybridObject: use it from the JavaScript thread only (it cannot be passed to a Worklet or another runtime). Every member is synchronous and blocks the JavaScript thread until Chilkat returns; a method that can take a while also exists as a ...Async twin returning a Promise, which runs the same call on a native worker thread so the UI keeps rendering. While such a call is pending, every other call on this object throws, except abort() and assigning onPercentDone / onProgressInfo.

dispose(): void

Releases the native object immediately instead of waiting for garbage collection (useful for a large BinData or an open socket). Calling it more than once is harmless; any other use of the object afterwards throws. An object with a pending ...Async call cannot be disposed until the promise settles.

Errors

A method that can fail throws a plain Error: a method whose only outcome is success or failure returns void and throws on failure; a method producing a string or an object returns it and throws where Chilkat would have returned null. The error's message is "Class.method(...): reason", where the reason is the last informative line of the object's lastErrorText, which holds the full Chilkat log of the failed call. A ...Async twin rejects its promise with the same Error instead of throwing. Properties never throw, and methods that answer a question (has..., is..., ...) return a plain boolean.

try {
  pdf.someMethod(...)
} catch (e) {
  console.log((e as Error).message)   // Pdf.someMethod(...): <reason>
  console.log(pdf.lastErrorText)   // the full Chilkat log of the failed call
}

// The same call without blocking the JavaScript thread:
try {
  await pdf.someMethodAsync(...)
} catch (e) {
  console.log((e as Error).message)   // Pdf.someMethodAsync: <reason>
}

Properties

DebugLogFilePath
// read/write
debugLogFilePath: string

If set to a file path, this property logs the LastErrorText of each Chilkat method or property call to the specified file. This logging helps identify the context and history of Chilkat calls leading up to any crash or hang, aiding in debugging.

Enabling the VerboseLogging property provides more detailed information. This property is mainly used for debugging rare instances where a Chilkat method call causes a hang or crash, which should generally not happen.

Possible causes of hangs include:

  • A timeout property set to 0, indicating an infinite timeout.
  • A hang occurring within an event callback in the application code.
  • An internal bug in the Chilkat code causing the hang.

More Information and Examples
top
HasCertificationSig
// read-only
readonly hasCertificationSig: boolean
Introduced in version 9.5.0.96

Returns true if the currently open PDF has a certification signature.

PDF defines two types of signatures: approval and certification.

The differences are as follows:

  • Approval: There can be any number of approval signatures in a document.
  • Certification: There can be only one certification signature and it must be the first one in a document.

top
LastErrorHtml
// read-only
readonly lastErrorHtml: string

Provides HTML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.

top
LastErrorText
// read-only
readonly lastErrorText: string

Provides plain text information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.

top
LastErrorXml
// read-only
readonly lastErrorXml: string

Provides XML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.

top
LastMethodSuccess
// read/write
lastMethodSuccess: boolean

Indicates the success or failure of the most recent method call: true means success, false means failure. This property remains unchanged by property setters or getters. This method is present to address challenges in checking for null or Nothing returns in certain programming languages. Note: This property does not apply to methods that return integer values or to boolean-returning methods where the boolean does not indicate success or failure.

top
NumEmbeddedFiles
// read-only
readonly numEmbeddedFiles: number
Introduced in version 9.5.0.95

The number of embedded files present in the currently open PDF.

More Information and Examples
top
NumPages
// read-only
readonly numPages: number
Introduced in version 9.5.0.85

The number of pages in the currently open PDF.

top
NumSignatures
// read-only
readonly numSignatures: number
Introduced in version 9.5.0.85

The number of digital signatures present in the currently open PDF.

top
OwnerPassword
// read/write
ownerPassword: string
Introduced in version 11.0.0

The PDF owner password, if required.

top
SigAllocateSize
// read/write
sigAllocateSize: number
Introduced in version 9.5.0.91

Defaults to 15000. This property should generally be left unchanged. If signing fails and the following message is in the LastErrorText: Did not allocate enough space for the PDF signature., then you should increase this value. The actual signature size will be noted in the LastErrorText, and you can use that value to set an allocation size that is somewhat larger.

top
UncommonOptions
// read/write
uncommonOptions: string
Introduced in version 9.5.0.85

This is a catch-all property to be used for uncommon needs. This property defaults to the empty string. It can be set to a list of one or more of the following comma separated keywords:

  • WriteStandardXref - When writing the PDF, write the cross reference section in standard format if possible. (The standard format is the older non-compressed format.)
  • NO_VERIFY_CERT_SIGNATURES - When countersigning a PDF (i.e. adding a new signature to a PDF that already contains one or more signatures), Chilkat will automatically validate the existing signatures and their certificates. (The signing certificates are typically embedded within a signature.) If any of these validations fail, the new signature is not added. Sometimes, an existing signature is validated, but the certs in the chain of authentication, such as issuer certs or root CA certs, are not included and not available to check. In this case, you can add the NO_VERIFY_CERT_SIGNATURES to skip the existing signature certificate validations.

top
UserPassword
// read/write
userPassword: string
Introduced in version 11.0.0

The PDF user password, if required.

top
VerboseLogging
// read/write
verboseLogging: boolean

If set to true, then the contents of LastErrorText (or LastErrorXml, or LastErrorHtml) may contain more verbose information. The default value is false. Verbose logging should only be used for debugging. The potentially large quantity of logged information may adversely affect peformance.

top
Version
// read-only
readonly version: string

Version of the component/library, such as "10.1.0"

More Information and Examples
top

Methods

AddEmbeddedFiles
addEmbeddedFiles(json: JsonObject, outFilePath: string): void
Introduced in version 9.5.0.97

Embeds one or more files in a PDF.

The json specifies the files to be attached to the PDF. See the linked example below.

The json is a JSON object containing an array of JSON objects, where each object can contain the following members.

  • localFilePath: (required) The local file to be embedded in the PDF.
  • description: (required) It is a short description of the embedded file.
  • subType: (optional) Specifies the file type, such as application/xml, text/plain, etc. If not specified, then Chilkat will automatically choose a subType based on the file extension.
  • embeddedFilename: (optional) Specifies the name of the file to be used within the PDF in the desire is for it to be different than the filename in the local filesystem. If not present, then the filename part of the localFilePath.
  • AFRelationship: (optional starting in v11.1.0) Specifies specify the nature of the relationship of the embedded file. Possible values are Source, Data, Alternative, Supplement, and Unspecified. If unset, the default is Alternative.

If successful, the updated PDF with embedded files is written to outFilePath.

Returns normally on success; throws an Error on failure.

More Information and Examples
top
AddEmbeddedFilesBd
addEmbeddedFilesBd(json: JsonObject, bd: BinData): void
Introduced in version 9.5.0.97

The same as AddEmbeddedFiles, but writes the resultant PDF to the bd.

Returns normally on success; throws an Error on failure.

More Information and Examples
top
AddSigningCert
addSigningCert(cert: Cert): void
Introduced in version 9.5.0.85

Adds a certificate to be used for PDF signing. To sign with more than one certificate, call AddSigningCert once per certificate.

Note: This method is used to provide the ability to sign once with multiple certificates. This is different than signing with one certificate, and then signing again with a different certificate.

Returns normally on success; throws an Error on failure.

top
AddVerificationInfo
addVerificationInfo(jsonOptions: JsonObject, outFilePath: string): void
Introduced in version 9.5.0.93

Adds LTV verification information to the PDF, and saves the updated PDF to outFilePath. This create or update a DSS (Document Security Store) in the PDF with the needed certificates, OCSP responses, and CRL information.

Pass an empty jsonOptions. The jsonOptions exists as a placeholder for adding options if needed.

Returns normally on success; throws an Error on failure.

top
AddVerificationInfoAsync
addVerificationInfoAsync(jsonOptions: JsonObject, outFilePath: string): Promise<void>
Introduced in version 9.5.0.93

Asynchronous form of AddVerificationInfo: the same call on a native worker thread, so the JavaScript thread (and the UI) stays responsive. Takes the same arguments and resolves with the same result. While the returned Promise is pending, every other call on this object throws (the object is busy), except abort(), which cancels the call, and assigning the onPercentDone / onProgressInfo callbacks, which report its progress.

Note: the onPercentDone and onProgressInfo callbacks run on the JavaScript thread while the promise is pending, so they can update the UI directly. A rejection's message is "Class.methodAsync: reason"; the full log is in lastErrorText.

Returns a Promise that resolves with the synchronous method's result (undefined for a void method) and rejects with an Error where the synchronous method would throw.

top
GetDss
getDss(json: JsonObject): void
Introduced in version 9.5.0.85

Gets the contents of the PDF's Document Security Store (/DSS) if it exists. Returns the information in JSON format (in json). If there is no /DSS then an empty JSON document {} is returned in json.

Returns normally on success; throws an Error on failure.

More Information and Examples
top
GetEmbeddedFileBd
getEmbeddedFileBd(index: number, bd: BinData): void
Introduced in version 9.5.0.95

Loads the bd with the contents of the Nth embedded file contained in the currently open PDF. The index specifies the index of the embedded file. The 1st embedded file is at index 0. See the example linked below.

Returns normally on success; throws an Error on failure.

More Information and Examples
top
GetEmbeddedFileInfo
getEmbeddedFileInfo(index: number, json: JsonObject): void
Introduced in version 9.5.0.95

Gets information about the Nth embedded file contained in the currently open PDF. The index specifies the index of the embedded file. The 1st embedded file is at index 0. The json is filled with information about the embedded file. See the example linked below.

Returns normally on success; throws an Error on failure.

More Information and Examples
top
GetLastJsonData
getLastJsonData(json: JsonObject): void
Introduced in version 11.0.0

Provides information about what transpired in the last method called. For many methods, there is no information. For some methods, details about what transpired can be obtained via LastJsonData. For example, after calling a method to verify a signature, the LastJsonData will return JSON with details about the algorithms used for signature verification.

top
GetMetadata
getMetadata(sb: StringBuilder): void
Introduced in version 9.5.0.92

If the PDF contains Metadata, then loads the Metadata XML into sb and returns true. If the PDF does not contain Metadata, then clears sb and returns false.

Returns normally on success; throws an Error on failure.

More Information and Examples
top
GetSignatureContent
getSignatureContent(index: number, bd: BinData): void
Introduced in version 9.5.0.92

Returns the CMS signature for the Nth signature contained in the PDF. The 1st signature is at index 0.

Returns normally on success; throws an Error on failure.

top
GetSignerCert
getSignerCert(index: number, cert: Cert): void
Introduced in version 9.5.0.87

This method retrieves the signer certificate after calling VerifySignature. Use the same index for index as the one passed to VerifySignature. If successful and the signer certificate is fully available, cert will contain the certificate.

Returns normally on success; throws an Error on failure.

More Information and Examples
top
GetUnsignedSigFields
getUnsignedSigFields(json: JsonObject): void
Introduced in version 9.5.0.90

Returns JSON containing the name of each unsigned signature field found in the PDF.

Returns normally on success; throws an Error on failure.

More Information and Examples
top
LoadBd
loadBd(pdfData: BinData): void
Introduced in version 9.5.0.85

Loads the PDF file contained in pdfData.

Returns normally on success; throws an Error on failure.

top
LoadFile
loadFile(filePath: string): void
Introduced in version 9.5.0.85

Load a PDF file into this object in memory.

Returns normally on success; throws an Error on failure.

top
SetHttpObj
setHttpObj(http: Http): void
Introduced in version 9.5.0.85

Sets the HTTP object to be used to communicate with the timestamp authority (TSA) server for cases where long term validation (LTV) of signatures is desired. The http is used to send the requests, and it allows for connection related settings and timeouts to be set. For example, if HTTP or SOCKS proxies are required, these features can be specified on the http.

The http is also used to send OCSP requests to store OCSP responses in the PDF's document security store (DSS).

More Information and Examples
top
SetSignatureJpeg
setSignatureJpeg(jpgData: BinData): void
Introduced in version 9.5.0.85

Provides an optional JPG image to be included in the signature appearance. The JPG data is passed in jpgData.

Note: JPG images must use the BaseLine format and not the Progressive format. (Programs typically save JPEG's using the BaseLine format as default.)

Returns normally on success; throws an Error on failure.

top
SetSigningCert
setSigningCert(cert: Cert): void
Introduced in version 9.5.0.85

Specifies a certificate to be used when signing the PDF. Signing requires both a certificate and private key. In this case, the private key is implicitly specified if the certificate originated from a PFX that contains the corresponding private key, or if on a Windows-based computer where the certificate and corresponding private key are pre-installed.

Returns normally on success; throws an Error on failure.

top
SetSigningCert2
setSigningCert2(cert: Cert, privateKey: PrivateKey): void
Introduced in version 9.5.0.85

Specifies a digital certificate and private key to be used for signing the PDF.

Returns normally on success; throws an Error on failure.

top
SignPdf
signPdf(jsonOptions: JsonObject, outFilePath: string): void
Introduced in version 9.5.0.85

Signs the open PDF and if successful writes the signed PDF to the ARG3. The jsonOptions contains information and instructions about the signature. See the examples below for more detailed information about the JSON options listed here.

Summary of PDF Signing Options

  • appearance.fillUnsignedSignatureField - Can be set to true) to tell Chilkat to sign an existing unsigned signature field. Chilkat will automatically scale the visual appearance (text + graphics) to fit the pre-existing signature field. When fillUnsignedSignatureField is specified, it is not necessary to set appearance.x, appearance.y, appearance.fontScale, etc.

    Starting in v9.5.0.90, the unsignedSignatureField option (see below) can be used to specify the unsigned signature field to be used. Otherwise, the 1st available unsigned field is used.

    See PDF Unsigned Signature Fields for more information.

  • appearance.fontScale - The font scale (in pts) to be used, such as 10.0.
  • appearance.height - Optional to specify the exact height of the visible signature rectangle in points, where 72 points equals 1 inch. If the appearance.height is set, then appearance.width should be set to auto (or left unset). Chilkat will compute the font scale to achieve the desired rectangle height, and the resulting width will depend on the text.
  • appearance.image - Indicates an image will be included in the signature. Set to the keyword custom-jpg to use an image set by calling the SetSignatureJpeg method. Otherwise can be set to one of the following keywords to indicate a built-in SVG graphic. (These are graphics embedded within the Chilkat library itself.)
    • green-check-grey-circle
    • green-check-green-circle
    • application-approved
    • application-rejected
    • document-accepted
    • approved
    • blue-check-mark
    • green-check-mark
    • green-check-grey-circle
    • red-x-red-circle
    • rejected
    • result-failure
    • result-pass
    • signature
    • document-check
    • document-x
    • red-x-grey-circle
  • appearance.imageOpacity - Sets the image opacity. Can be an integer from 1 to 100.
  • appearance.imagePlacement - Sets the image placment within the signature rectangle. Can be left, right, or center. Images placed in the center typically have opacity 50% or less because the text is displayed over the image (i.e. it is a background image). Images placed left or right are not background images. The signature rectangle is divided into two sub-rectangles, one for the image, and one for the text.
  • appearance.margin_x - If the appearance.x is set to left, then this can optionally be use to specify the position from the left edge. The default margin is 10.0 (10 points, where 72 points equals 1 inch).
  • appearance.margin_y - If the appearance.y is set to top, then this can optionally be use to specify the position from the top. The default margin for y is 20.0 (20 points, where 72 points equals 1 inch).
  • appearance.text[i] - The text that should appear in the signature box. Each line is specified in a JSON array item, where i is an integer starting with 0 as the 1st line. The text can contain the following keywords which are replaced with actual values:
    • cert_country - The signing certificate's subject country (C).
    • cert_cn - The signing certificate's subject common name (CN).
    • cert_dn - The signing certificate's DN (distinguished name).
    • cert_email - The signing certificate's subject email address (E).
    • cert_issuer_cn - The signing certificate's issuer's common name (CN).
    • cert_locality - The signing certificate's subject locality (L).
    • cert_organization - The signing certificate's subject organization (O).
    • cert_org_id - The signing certificate's organization ID.
    • cert_ou - The signing certificate's subject organizational unit (OU).
    • cert_san_rfc822name - The signing certificate's RFC822 subject alternative name.
    • cert_serial_dec - The signing certificate's serial number in decimal format.
    • cert_serial_hex - The signing certificate's serial number in hex format.
    • cert_state - The signing certificate's subject state (S).
    • cert_thumbprint - The signing certificate's thumbprint (The SHA1 hash of the binary DER representation in hex format).
    • current_datetime - Current local date/time in the format such as Sep 11 2020 16:30:54.
    • current_dt - Current local date/time in PDF date/time string format, such as YYYY.MM.DD hh:mm:ss -05'00'.
    • current_rfc822_dt_gmt - Current GMT date/time in RFC822 format, such as Mon, 22 Nov 2021 15:58:41 GMT.
    • current_rfc822_dt_local - Current local date/time in RFC822 format, such as Mon, 22 Nov 2021 09:56:16 -0600.
    • current_timestamp_gmt - Current GMT date/time in timestamp format, such as 1990-12-31T23:59:60Z.
    • current_timestamp_local - Current local date/time in timestamp format, such as 2019-10-12T03:20:50.52-04:00.
  • appearance.width - Optional to specify the exact width of the visible signature rectangle in points, where 72 points equals 1 inch. If the appearance.width is set, then appearance.height should be set to auto (or left unset). Chilkat will compute the font scale to achieve the desired rectangle width, and the resulting height will depend on the text and number of lines of text.
  • appearance.x - The horizontal position on the page of the left edge of the signature box. Can be a keyword such as left, right, or middle to specify a typical placement with default margins. Otherwise can be a floating point number where 0.0 is the leftmost coordinate of a page, and 612.0 is the right most. Can also be the keyword after to place the signature just to the right of the rightmost signature on the page.
  • appearance.y - The vertical position on the page of the top edge of the signature box. Can be one of the keywords top or bottom to specify a typical placement with default margins. Otherwise can be a floating point number where 0.0 is the bottom coordinate of a page, and 792.0 is the top. Can also be the keyword under to place the signature just under the bottommost signature on the page.
  • contactInfo - Optional to provide free-form text with contact information about the signer.
  • docMDP.add - Set this boolean value to true to include the Document MDP Permissions with a certifying signature. When a certifying signature is desired, both lockAfterSigning and docMDP.add should be specified. The default Doc MDP permission level is 2.
  • docMDP.accessPermissions - Include this if the docMDP.add is specified, and a permission level different from the default value of 2 is desired. Possible values are:
    • 1: No changes to the document are permitted and any changes invalidate the signature.
    • 2: Permitted changes include filling in forms, instantiating page templates and signing.
    • 3: Same as 2, but also allow annotation creation, deletion, and modification.
  • embedCertChain - Boolean to control whether the certificate chain is included in the signature. The default is to include the certificates in the chain of authentication. Set this to false to only include the signing certificate (this is not common).
  • hashAlgorithm - If the signing certificate is RSA-based, and the signing scheme (padding scheme) is RSA-PSS, then this specifies the PSS hash algorithm. Can be sha1, sha256, sha384, or sha512. (sha256 is what should be commonly chosen.)
  • includeRootCert - Boolean to control whether the root CA certificate is included in the certificate chain (assuming the certificate chain is included). The default is to include the root CA certificate. Set this to false to exclude the root CA certificate from being included (this is not common).
  • info.* - (added in Chilkat v9.5.0.90) Provides the ability to add or update the PDF document's /Info, such as Creator, Producer, Title, etc. Any number of arbitrary member names can be specified and these will be added to the document's /Info dictionary. However, Chilkat will ignore ModDate and CreationDate because ModDate is automatically set to the current system date/time and the CreationDate should not change.
  • invisibleSignature - Set this boolean to true to create an invisible signature with no appearance.
  • legalAttestation - Set to provide a free-form text legal attestation.
  • location - Optional to provide free-form text with a description of the geographic location where the PDF was signed.
  • lockAfterSigning - Set this boolean to true to certify and lock a PDF as opposed to adding an approval signature (the default) which allows for additional countersignatures.
  • ltvOcsp - Set this boolean to true to create an LTV-enabled signature.
  • noDss - Set this boolean to true to prevent adding a /DSS (Document Security Store).
  • page - The page number where the signature will be placed. Page 1 is the 1st page.
  • reason - Optional to provide text indicating the reason for the signature.
  • signingAlgorithm - If the signing certificate is RSA-based, then chooses the RSA padding scheme. Possible values are pkcs for PKCS-v1_5 or pss for RSASSA-PSS.
  • signingCertificateV2 - Set to 1 to include the SigningCertificateV2 authenticated attribute. This is desired in most cases.
  • signingTime - Set to 1 to include the SigningTime authenticated attribute. This is desired in most cases. Note: This is not the same as time-stamping. This is a fundamental authenticated attribute that should be included with or without the addition of time-stamping.
  • sigTextLabel - Set to provide free-form text for the signatures annotation text label.
  • subFilter - Set to /ETSI.CAdES.detached, /adbe.pkcs7.detached, or something else.
  • timestampToken.enabled - Set to true to tell Chilkat to request a timestamp from a TSA server and include the timestamp token in the signature's authentication attributes
  • timestampToken.tsaUrl - The timestamp server's URL.
  • timestampToken.tsaUsername, timestampToken.tsaPassword - If the timestamp server requires a login and password.
  • timestampToken.bearerToken - Use this if the timestamp server requires a bearer token instead of a password. This feature was added in Chilkat v11.2.0.
  • timestampToken.requestTsaCert - Set to true to ask the timestamp server to include its certificate in the timestamp token.
  • unsignedSignatureField - (added in Chilkat v9.5.0.90) Can be set to specify the name of the unsigned signature field that is to be signed.

Returns normally on success; throws an Error on failure.

More Information and Examples
top
SignPdfAsync
signPdfAsync(jsonOptions: JsonObject, outFilePath: string): Promise<void>
Introduced in version 9.5.0.85

Asynchronous form of SignPdf: the same call on a native worker thread, so the JavaScript thread (and the UI) stays responsive. Takes the same arguments and resolves with the same result. While the returned Promise is pending, every other call on this object throws (the object is busy), except abort(), which cancels the call, and assigning the onPercentDone / onProgressInfo callbacks, which report its progress.

Note: the onPercentDone and onProgressInfo callbacks run on the JavaScript thread while the promise is pending, so they can update the UI directly. A rejection's message is "Class.methodAsync: reason"; the full log is in lastErrorText.

Returns a Promise that resolves with the synchronous method's result (undefined for a void method) and rejects with an Error where the synchronous method would throw.

top
SignPdfBd
signPdfBd(jsonOptions: JsonObject, bd: BinData): void
Introduced in version 9.5.0.94

Signs the open PDF and if successful writes the signed PDF to the bd. The jsonOptions contains information and instructions about the signature. See the reference documentation for the SignPdf method for details about jsonOptions.

Returns normally on success; throws an Error on failure.

top
SignPdfBdAsync
signPdfBdAsync(jsonOptions: JsonObject, bd: BinData): Promise<void>
Introduced in version 9.5.0.94

Asynchronous form of SignPdfBd: the same call on a native worker thread, so the JavaScript thread (and the UI) stays responsive. Takes the same arguments and resolves with the same result. While the returned Promise is pending, every other call on this object throws (the object is busy), except abort(), which cancels the call, and assigning the onPercentDone / onProgressInfo callbacks, which report its progress.

Note: the onPercentDone and onProgressInfo callbacks run on the JavaScript thread while the promise is pending, so they can update the UI directly. A rejection's message is "Class.methodAsync: reason"; the full log is in lastErrorText.

Returns a Promise that resolves with the synchronous method's result (undefined for a void method) and rejects with an Error where the synchronous method would throw.

top
UpdateMetadata
updateMetadata(sb: StringBuilder, outFilePath: string): void
Introduced in version 10.1.0

Updates or adds XMP metdata to a PDF. The metadata is passed in sb. If successful, the PDF with updated or inserted metadata is written to outFilePath.

Returns normally on success; throws an Error on failure.

top
UpdateMetadataBd
updateMetadataBd(sb: StringBuilder, bd: BinData): void
Introduced in version 10.1.0

Updates or adds XMP metdata to a PDF. The metadata is passed in sb. If successful, the PDF with updated or inserted metadata is written to bd.

Returns normally on success; throws an Error on failure.

top
VerifySignature
verifySignature(index: number, sigInfo: JsonObject): void
Introduced in version 9.5.0.85

Verifies the Nth signature contained in the PDF, where the 1st signature is indicated by an index of 0. Returns true if the signature valid, otherwise returns false. The sigInfo is an output argument and is populated with information about the validated or unvalidated signature.

Returns normally on success; throws an Error on failure.

More Information and Examples
top

Events

While a method runs, Pdf reports progress through two optional callback properties. Assign a function to receive the event, or undefined to stop receiving it. The callbacks are delivered on the JavaScript thread, so they are useful with the ...Async methods: during a synchronous call the JavaScript thread is busy inside Chilkat, and the events can only arrive after it returns.

const pdf = new Pdf()
pdf.onPercentDone = (pct) => setProgress(pct)          // pct is 0..100
pdf.onProgressInfo = (name, value) => console.log(`${name}: ${value}`)
pdf.heartbeatMs = 250   // let abort() take effect within a quarter second

const pending = pdf.someMethodAsync(...)
cancelButton.onPress = () => pdf.abort()   // the promise then rejects
await pending

PercentDone fires when an operation's completion percentage is known; ProgressInfo delivers named progress values (what is reported depends on the class and method). There is no AbortCheck callback: to cancel a pending ...Async call, call abort() on the object. Chilkat notices the request at its next progress check, which happens at least every heartbeatMs milliseconds on the classes that have that property (0, the default, disables the heartbeat, so set it for a responsive cancel), and the promise rejects with Chilkat's abort error. abort() is harmless when nothing is pending.

PercentDone
// callback property; assign undefined to remove
onPercentDone?: (pctDone: number) => void

This provides the percentage completion for any method involving network communications or time-consuming processing, assuming the progress can be measured as a percentage. This event is triggered only when it's possible and logical to express the operation's progress as a percentage. The pctDone argument will range from 1 to 100. For methods that finish quickly, the number of PercentDone callbacks may vary, but the final callback will have pctDone equal to 100. For longer operations, callbacks will not exceed one per percentage point (e.g., 1, 2, 3, ..., 98, 99, 100).

The PercentDone callback also acts as an AbortCheck event. For fast methods where PercentDone fires, an AbortCheck event may not trigger since the PercentDone callback already provides an opportunity to abort. For longer operations, where time between PercentDone callbacks is extended, AbortCheck callbacks enable more responsive operation termination.

To abort the operation, set the abort output argument to true. This will cause the method to terminate and return a failure status or corresponding failure value.

More Information and Examples

Example:

pdf.onPercentDone = (pct) => {
  // pct ranges from 0 to 100.
  setProgress(pct)   // runs on the JavaScript thread: React state may be updated directly
}
await pdf.someMethodAsync(...)
// To stop an operation from within the callback, call pdf.abort()
top
ProgressInfo
// callback property; assign undefined to remove
onProgressInfo?: (name: string, value: string) => void

This event callback provides tag name/value pairs that detail what occurs during a method call. To discover existing tag names, create code to handle the event, emit the pairs, and review them. Most tag names are self-explanatory.

Note: Some Chilkat methods don't fire any ProgressInfo events.

More Information and Examples

Example:

pdf.onProgressInfo = (name, value) => console.log(`${name}: ${value}`)
await pdf.someMethodAsync(...)
top