Class: Instance

PSPDFKit.Instance

A mounted document instance.

You can generate an instance by using PSPDFKit.load.

Namespaces

Members

Methods

Type Definitions




Members

(readonly) annotationCreatorName: string|null

The current annotation creator name. This is set using instance.setAnnotationCreatorName().

Type:
  • string | null

(readonly) annotationPresets: Object.<string, PSPDFKit.AnnotationPreset>

Returns a deep copy of the latest annotation presets. This value changes whenever the user interacts with PSPDFKit or whenever PSPDFKit.Instance.setAnnotationPresets is called.

Mutating this object will have no effect.

Type:

(readonly) connectedClients: Immutable.Map.<string, PSPDFKit.InstantClient>
Server Only

NOTE This method is only available with PSPDFKit Instant.

Use this method to obtain an up-to-date list of the current connected instance clients.

The return value is an Immutable.Map, which can be used like the regular ES2015 Map.

The PSPDFKit.Instance~ConnectedClientsChangeEvent will be triggered, whenever a new client will connect to the document, or a current client will disconnect. The event will always include the full up-to-date list of the currently connected clients (the same that would be returned when you call this method).

Type:
Examples

Find out how many total clients are currently connected

instance.connectedClients.count();

Find out how many distinct users are currently connected

instance.connectedClients.groupBy(c => c.userId).count();

Find out how many anonymous clients are currently connected

instance.connectedClients.filter(c => !c.userId).count();

(readonly) contentDocument: Document|ShadowRoot

Access the shadow root object of the PSPDFKit for Web viewer. This can be used to quickly interact with elements (using our public CSS API) inside the viewer.

When the iframe fallback is set, this property provides access the document object of the PSPDFKit for Web viewer frame instead.

Type:
  • Document | ShadowRoot
Example
instance.contentDocument.addEventListener("mouseup", handleMouseUp);

(readonly) contentWindow: window

Access the window object of the PSPDFKit for Web viewer frame. This can be used to quickly interact with elements (using our public CSS API) inside the viewer.

Type:
  • window
Example
instance.contentWindow.location;

(readonly, nullable) currentAnnotationPreset: string

Get the current active annotation preset ID

Type:
  • string

(readonly) currentZoomLevel: number

The current zoom level. This will be either the number set in the current PSPDFKit.ViewState or calculated using the PSPDFKit.ZoomMode.

Type:
  • number

(readonly) disablePointSnapping: boolean

Whether to disable snapping to points when creating annotations for measurement tools

Type:
  • boolean
Example
instance.setViewState(viewState => viewState.set('disablePointSnapping', true))

(readonly) documentEditorFooterItems: Array.<PSPDFKit.DocumentEditorFooterItem>

Returns a deep copy of the latest document editor footer items. This value changes whenever the user interacts with PSPDFKit or whenever PSPDFKit.Instance.setDocumentEditorFooterItems is called.

Mutating this array will have no effect.

Type:

(readonly) documentEditorToolbarItems: Array.<PSPDFKit.DocumentEditorToolbarItem>

Returns a deep copy of the latest document editor toolbar items. This value changes whenever the user interacts with PSPDFKit or whenever PSPDFKit.Instance.setDocumentEditorToolbarItems is called.

Mutating this array will have no effect.

Type:

(readonly) editableAnnotationTypes: PSPDFKit.Immutable.Set.<PSPDFKit.Annotation>

Returns a deep copy of the latest editableAnnotationTypes. This value changes whenever PSPDFKit.Instance.setEditableAnnotationTypes is called.

Mutating this object will have no effect.

Type:
  • PSPDFKit.Immutable.Set.<PSPDFKit.Annotation>

(readonly) locale: string

Returns the current locale for the application.

Type:
  • string

(readonly) maximumZoomLevel: number

The maximum zoom level. This value depends on the current viewport and page dimensions. Defaults to 10 but can be bigger so that the FIT_TO_WIDTH and FIT_TO_VIEWPORT PSPDFKit.ZoomModes always fit.

Type:
  • number

(readonly) minimumZoomLevel: number

The minimum zoom level. This value depends on the current viewport and page dimensions. Defaults to 0.5 but can be bigger so that the FIT_TO_WIDTH and FIT_TO_VIEWPORT PSPDFKit.ZoomModes always fit.

Type:
  • number

(readonly) searchState: PSPDFKit.SearchState

Returns the latest search state. This value changes whenever the user interacts with PSPDFKit or whenever PSPDFKit.Instance.setSearchState is called.

The search state can be used to finely control the current search UI.

Type:

(readonly) stampAnnotationTemplates: Array.<(PSPDFKit.Annotations.StampAnnotation|PSPDFKit.Annotations.ImageAnnotation)>

Returns a deep copy of the latest stamp and image annotation templates. This value changes whenever PSPDFKit.Instance#setStampAnnotationTemplates is called.

Mutating this array will have no effect.

Type:

(readonly) toolbarItems: Array.<PSPDFKit.ToolbarItem>

Returns a deep copy of the latest toolbar items. This value changes whenever the user interacts with PSPDFKit or whenever PSPDFKit.Instance.setToolbarItems is called.

Mutating this array will have no effect.

Type:

(readonly) totalPageCount: number

Get the total number of pages for this document

Type:
  • number

(readonly) viewState: PSPDFKit.ViewState

Returns the latest view state. This value changes whenever the user interacts with PSPDFKit or whenever PSPDFKit.Instance.setViewState is called.

When you want to keep a reference to the latest view state, you should always listen on the PSPDFKit.Instance~ViewStateChangeEvent to update your reference.

Type:

(readonly) zoomStep: number

Type:
  • number

Methods

abortPrint()

Aborts the current print job.

Throws:

This method will throw when printing is disabled or no printing is currently being processed.

Type
PSPDFKit.Error

addEventListener(action, listener)

This method is used to register event listeners for one of the following events:

The behavior of this method is influenced by the DOM API. It requires an action and a listener. Removing the listener will need the same reference to the listener function. The action name is always starting with a lowercase letter, for example: viewState.change for PSPDFKit.Instance~ViewStateChangeEvent

You can add multiple listeners of the same event types as you would expect. Event listeners can be removed by calling PSPDFKit.Instance#removeEventListener.

When the supplied event is not in the above list, this method will throw a PSPDFKit.Error.

Parameters:
Name Type Description
action string

The action you want to add an event listener to. See the above list for possible event types.

listener function

A listener function.

Throws:

Will throw an error when the supplied event is not valid.

Type
PSPDFKit.Error
Examples

Adding a listener for the view state changed event

instance.addEventListener("viewState.change", (viewState) => {
  console.log(viewState.toJS());
});

Adding an unknown event will raise an error.

try {
  instance.addEventListener("doesnotexist", () => {});
} catch (error) {
  (error instanceof PSPDFKit.Error); // => true
}

applyOperations(operations) → {Promise.<void>}

Applies operations to the current document. If multiple operations are provided, each operation is performed on the resulting document from the previous operation. This API works only if you have the document editor component in your license.

Parameters:
Name Type Description
operations Array.<PSPDFKit.DocumentOperation>

Operations to be performed on the document.

Returns:

Promise that resolves with an array of results.

Type
Promise.<void>
Example

Apply 90 degrees rotation to page 0

instance
  .applyOperations([
    {
      type: "rotatePages",
      pageIndexes: [0],
      rotateBy: 90
    }
  ]);

applyRedactions() → {Promise.<void>}

Applies redactions to the current document. This will overwrite the document, removing content irreversibly.

In the process of redacting the content, all the redaction annotations will be removed. Any annotation that is either partially or completely covered by a redaction annotation will be deleted.

Returns:

Promise that resolves when the redactions has been applied.

Type
Promise.<void>
Example

Applies redactions

instance.applyRedactions().then(function() {
  console.log("The document has been redacted.");
});

calculateFittingTextAnnotationBoundingBox(annotation) → {PSPDFKit.Annotations.TextAnnotation}

Takes a PSPDFKit.Annotations.TextAnnotation and returns a new PSPDFKit.Annotations.TextAnnotation where the bounding box is adjusted to fit the annotation and inside the page.

This is using the same calculations as the text annotation editor interface.

Parameters:
Name Type Description
annotation PSPDFKit.Annotations.TextAnnotation

The text annotation that needs it's bounding box adjusted.

Returns:

The text annotation that has it's bounding box adjusted.

Type
PSPDFKit.Annotations.TextAnnotation
Example
textAnnotation = instance.calculateFittingTextAnnotationBoundingBox(textAnnotation);

compareDocuments(operation, comparisonDocuments) → {Promise.<DocumentComparisonResult>}

Compares documents based on the operations provided and returns an object containing the results and errors in the same order as the operations.

Parameters:
Name Type Description
operation ComparisonOperation

The comparison operations to be applied.

comparisonDocuments ComparisonDocuments

Descriptors of the original and changed documents.

Returns:
  • A promise that resolves to results of the comparison.
Type
Promise.<DocumentComparisonResult>
Example

Compare two documents

const operation = new PSPDFKit.ComparisonOperation("text", { numberOfContextWords: 2 });

const originalDocument = new PSPDFKit.DocumentDescriptor({ filePath: "path/to/original.pdf", pageIndexes: [0]});
const changedDocument = new PSPDFKit.DocumentDescriptor({ filePath: "path/to/changed.pdf", pageIndexes: [0]});

const comparisonDocuments = { originalDocument, changedDocument };

instance.compareDocuments(operation, comparisonDocuments)
  .then((comparisonResults) => {
    console.log(comparisonResults);
  });

create(changes) → {Promise.<Array.<PSPDFKit.Change>>}

Creates new changes and assigns them IDs. If you need to ensure that changes are persisted by the backend, please refer to: PSPDFKit.Instance#ensureChangesSaved.

This method returns a promise that will resolve to an array of records with the local IDs set.

New changes will be made visible in the UI instantly.

Parameters:
Name Type Description
changes PSPDFKit.Change | Array.<PSPDFKit.Change> | List.<PSPDFKit.Change>

A single change or a list/array of changes that should be created.

Returns:

A promise that resolves to an array of created changes or an error if some changes could not be created.

Type
Promise.<Array.<PSPDFKit.Change>>
Example
PSPDFKit.load(configuration).then(function(instance) {
  const annotation = new PSPDFKit.Annotations.InkAnnotation({
    pageIndex: 0,
    lines: PSPDFKit.Immutable.List([
      PSPDFKit.Immutable.List([
        new PSPDFKit.Geometry.DrawingPoint({ x: 0,   y: 0  }),
        new PSPDFKit.Geometry.DrawingPoint({ x: 100, y: 100}),
      ])
    ])
  });
  instance.create(annotation).then(function(createdAnnotations) {
    console.log(createdAnnotations);
  });
})

createAttachment(blob) → {Promise.<string>}

Creates a new attachment and returns a Promise that resolves to the created attachments ID.

Parameters:
Name Type Description
blob Blob

The attachment data as a Blob object.

Throws:

Will throw an error when the file can not be read.

Type
PSPDFKit.Error
Returns:

A promise that resolves to the attachment ID.

Type
Promise.<string>
Example
PSPDFKit.load(configuration).then(function(instance) {
  instance.createAttachment(blob).then(function(attachmentId) {
    console.log(attachmentId);
  });
})

createRedactionsBySearch(term, options) → {Promise.<PSPDFKit.Immutable.List.<string>>}

Searches in the PDF document and creates a redaction annotation for each search result. You can search for a text, regex or use one of the patterns we provide. See PSPDFKit.SearchPattern for the list of all the patterns we support.

Regex syntax:

Notice that matches included when using one of the PSPDFKit.SearchPattern options might overfit the criteria (i.e. include false positive results). This might happen since we strive for including all positive results and avoid data loss. Make sure to review the matches found.

Note for multiline regular expressions that document text lines end with CRLF (\r\n).

Regular expressions that follow the JavaScript syntax are matched in a similar way to the RegExp.prototype.exec() method (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec), but ignoring capturing groups, that is, this function only returns full string matches.

Parameters:
Name Type Description
term string | PSPDFKit.SearchPattern

The text, regex or pattern you want to search for.

options object

Search options object:

  • searchType {PSPDFKit.SearchType} Redactions Search Type. Default is PSPDFKit.SearchType.TEXT
  • searchInAnnotations {boolean} set to false if you don't want to search in annotations. Default is true
  • caseSensitive {boolean} Whether the search will be case-sensitive or not. Default is false if searchType is PSPDFKit.SearchType.TEXT and true for other types of searches.
  • annotationPreset {PSPDFKit.RedactionAnnotationPreset} Redaction annotation preset
  • startPageIndex {number} The page number to start the search from. Default is 0
  • pageRange {number} Starting from the start page, the number of pages to search. Default is to the end of the document.
Returns:

Promise that resolves when the redaction annotations have been created. Returns a list of new Redaction Annotation IDs.

Type
Promise.<PSPDFKit.Immutable.List.<string>>
Example

Search and add redactions

instance.createRedactionsBySearch(PSPDFKit.SearchPattern.CREDIT_CARD_NUMBER, {
  searchType: PSPDFKit.SearchType.PRESET,
  searchInAnnotations: true,
 annotationPreset: {
    overlayText: 'Redacted'
  }
}).then(function(ids) {
  console.log("The following annotations have been added:", ids);

  return instance.applyRedactions();
});

// We can add an "annotations.create" event listener and add custom logic based on the
// information for each of the newly created redaction annotations

const {RedactionAnnotation} = PSPDFKit.Annotations
instance.addEventListener("annotations.create", annotations => {
  const redactions = annotations.filter(annot => annot instanceof RedactionAnnotation)
  if (redactions.size > 0) {
    console.log("Redactions: ", redactions.toJS())
  }
});

delete(changeIds) → {Promise.<Array.<PSPDFKit.Change>>}

Deletes a change. This can be called with a change ID.

If you need to ensure that changes are persisted by the backend, please refer to: PSPDFKit.Instance#ensureChangesSaved.

Deleted changes will be made visible in the UI instantly.

If the deleted change is a PSPDFKit.Annotations.WidgetAnnotation (which can only be deleted if the Form Creator component is present in the license, and the backend is using a Form Creator capable provider), and the associated PSPDFKit.FormField only includes that annotation in its annotationIds list, the form field will also be deleted.

If there are more widget annotations remaining in the annotationIds list, as could be the case for radio buttons, for example, the form field's annotationIds property will be updated by removing the deleted annotation's id from it.

Parameters:
Name Type Description
changeIds string | Array.<string> | List.<string>

A single id or a list/array of ids of changes that should be deleted.

Returns:

A promise that resolves to an array of deleted changes or an error if some changes could not be deleted.

Type
Promise.<Array.<PSPDFKit.Change>>
Example
PSPDFKit.load(configuration).then(function(instance) {
  instance.delete(1).then(function() {
    console.log("Object with ID 1 deleted.");
  });
});

deleteAnnotationsGroup(annotationGroupKey)

If there are any annotations groups, this function will return all annotations groups. deleteAnnotationsGroup

Parameters:
Name Type Description
annotationGroupKey string

The annotation group key.

ensureChangesSaved(changes) → {Promise.<Array.<PSPDFKit.Change>>}

Ensures that changes have been saved to the backend and returns the current persisted state of these changes.

This method returns a promise that will resolve to an array of Change.

Parameters:
Name Type Description
changes PSPDFKit.Change | Array.<PSPDFKit.Change> | List.<PSPDFKit.Change>

A single change or a list/array of changes to ensure saved.

Returns:

A promise that resolves to an array of changes or an error if some changes could not be saved.

Type
Promise.<Array.<PSPDFKit.Change>>
Example
PSPDFKit.load(configuration).then(function(instance) {
  instance.create(newAnnotation)
    .then(instance.ensureChangesSaved)
    .then(function() {
      console.log('Annotation persisted by annotation provider');
    });
});

exportInstantJSON(version) → {Promise.<object>}

Instant JSON can be used to instantiate a viewer with a diff that is applied to the raw PDF. This format can be used to store annotation and form field value changes on your server and conveniently instantiate the viewer with the same content at a later time.

Instead of storing the updated PDF, this serialization only contains a diff that is applied on top of the existing PDF and thus allows you to cache the PDF and avoid transferring a potentially large PDF all the time.

This method is used to export the current annotations as Instant JSON. Use PSPDFKit.Configuration#instantJSON to load it.

annotations will follow the Instant Annotation JSON format specification. formFieldValues will follow the Instant Form Field Value JSON format specification.

Optionally a version argument can be provided to specify the Instant JSON version to use for exported annotations.

For Server-Backed setups, only saved annotations will be exported.

Parameters:
Name Type Description
version number

Optional Instant JSON version for annotations.

Returns:

Instant JSON as a plain JavaScript object.

Type
Promise.<object>
Example
instance.exportInstantJSON().then(function (instantJSON) {
  // Persist it to a server
  fetch("https://example.com/annotations", {
    "Content-Type": "application/json",
    method: "POST",
    body: JSON.stringify(instantJSON)
  }).then(...);
});

exportOffice(options, format) → {Promise.<ArrayBuffer>}

Exports the document converted to the specified output format as an ArrayBuffer. This can be used to download the resulting file.

An options object should be passed to the method with a format property set to one of the supported conversion output formats: PSPDFKit.OfficeDocumentFormat.

Parameters:
Name Type Description
options object

Export options object:

format object.format

one of PSPDFKit.OfficeDocumentFormat values.

Returns:

The binary contents of the PDF.

Type
Promise.<ArrayBuffer>
Example

Download as DOCX

instance.exportOffice({ format: PSPDFKit.OfficeDocumentFormat.docx })
  .then(function (buffer) {
    const blob = new Blob([buffer], { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" });
    const objectUrl = window.URL.createObjectURL(blob);
    downloadPdf(objectUrl);
    window.URL.revokeObjectURL(objectUrl);
  });

function downloadPdf(blob) {
  const a = document.createElement("a");
  a.href = blob;
  a.style.display = "none";
  a.download = "download.docx";
  a.setAttribute("download", "download.docx");
  document.body.append(a);
  a.click();
  a.remove();
}

exportPDF(flags) → {Promise.<ArrayBuffer>}

Exports the PDF contents as an ArrayBuffer. This can be used to download the PDF.

An options object can be passed to the method with the following flags:

  • flatten, which will visually embed annotations and form fields in the document and remove them from the document's data.
  • incremental, which will force the document to be incrementally saved if true.
  • excludeAnnotations, which will exclude annotations from the exported document.
  • saveForPrinting, which will exclude annotations that have the noPrint flag set to true from the exported document (Standalone only);
  • includeComments, which will include comments in the exported document (Server-Backed only).
  • permissions, which protects the PDF with a password.
  • outputFormat, which allows you to export a PDF in PDF/A format.
  • optimize, which allows optimization of the document to be exported (Server-Backed only).

If the document is digitally signed and the license includes the Digital Signatures component, the method will export the document incrementally saved by default, so as not to corrupt signed data. Otherwise, it will be exported as fully saved by default.

It's not possible to use flatten and incremental both set to true at the same time, as flattening is a destructive operation that will necessarily modify the provided document.

Please see this guide article for more information and examples.

Parameters:
Name Type Description
flags object

Export options object:

  • flatten {boolean} Default: false. Whether the document annotations should be converted to PDF content and therefore not editable in the future.
  • incremental {boolean} Default: false, or true if the document is digitally signed and the license includes the Digital Signatures component. Whether the document should be exported using "full" or "incremental" saving (Standalone only).
  • excludeAnnotations {boolean} Default: false. Whether the document annotations should be exported.
  • saveForPrinting only supported in Standalone setups. {boolean} Default: false.
  • includeComments only supported in Server-Backed setups. {boolean} Default: true.
  • flattenElectronicSignatures {boolean} Default: value of flatten. Allows flattening Electronic Signatures and removing their associated form fields so they are visible in other viewers that otherwise would hide them.
  • permissions {Object}. Contain the userPassword and ownerPassword to encrypt the PDF along with the documentPermissions. permissions.userPassword {string}. The user password to encrypt the PDF. permissions.ownerPassword {string}. The owner password to encrypt the PDF. permissions.documentPermissions {DocumentPermissions} . An Array that specifies what users can do with the output PDF.
  • outputFormat boolean | {conformance?: Conformance, vectorization?: boolean, rasterization?: boolean} Defaults to false. If set to true, a default set of options will be applied to the exported document:
{
  conformance: PSPDFKit.Conformance.PDFA_2B,
  vectorization: true,
  rasterization: true,
}

Instead of a boolean value you can pass your own object ith custom values for the properties above.

Parameters vectorization and rasterization are only supported in Document Engine mode.

  • optimize: only supported in Document Engine mode
`boolean |
{
  documentFormat?: 'pdf' | 'pdfa',
  grayscaleText: boolean,
  grayscaleGraphics: boolean,
  grayscaleFormFields: boolean,
  grayscaleAnnotations: boolean,
  grayscaleImages: boolean,
  disableImages: boolean,
  mrcCompression: boolean,
  imageOptimizationQuality: 1 | 2 | 3 | 4,
  linearize: boolean,
}

Defaults to false. If set to true the exported document will have a default set of options:

{
  documentFormat: 'pdf',
  grayscaleText: false,
  grayscaleGraphics: false,
  grayscaleFormFields: false,
  grayscaleAnnotations: false,
  grayscaleImages: false,
  disableImages: false,
  mrcCompression: false,
  imageOptimizationQuality: 2,
  linearize: false,
}

Otherwise, you can pass the above options object customised with your own values instead of a boolean value.

Returns:

The binary contents of the PDF.

Type
Promise.<ArrayBuffer>
Examples

Export the PDF content

instance.exportPDF().then(function (buffer) {
  buffer; // => ArrayBuffer
});

Export the PDF with password and permissions

instance.exportPDF({
   permissions: {
     userPassword: "123",
     ownerPassword: "123",
     documentPermissions: [PSPDFKit.DocumentPermissions.annotationsAndForms]
   }
}).then(function (buffer) {
  buffer; // => ArrayBuffer
});

Download the PDF by using an `<a>` tag

instance.exportPDF().then(function(buffer) {
  const supportsDownloadAttribute = HTMLAnchorElement.prototype.hasOwnProperty(
    "download"
  );
  const blob = new Blob([buffer], { type: "application/pdf" });
  if (navigator.msSaveOrOpenBlob) {
    navigator.msSaveOrOpenBlob(blob, "download.pdf");
  } else if (!supportsDownloadAttribute) {
    const reader = new FileReader();
    reader.onloadend = function() {
      const dataUrl = reader.result;
      downloadPdf(dataUrl);
    };
    reader.readAsDataURL(blob);
  } else {
    const objectUrl = window.URL.createObjectURL(blob);
    downloadPdf(objectUrl);
    window.URL.revokeObjectURL(objectUrl);
  }
});
function downloadPdf(blob) {
  const a = document.createElement("a");
  a.href = blob;
  a.style.display = "none";
  a.download = "download.pdf";
  a.setAttribute("download", "download.pdf");
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

exportPDFWithOperations(operations) → {Promise.<ArrayBuffer>}

Exports the PDF contents after applying operations on the current document, which is not modified. If multiple operations are provided, each operation is performed on the resulting document from the previous operation. Returns an ArrayBuffer that can be used to download the PDF.

Parameters:
Name Type Description
operations Array.<PSPDFKit.DocumentOperation>

Operations to be performed on the document.

Returns:

Promise that resolves with the binary contents of the modified PDF.

Type
Promise.<ArrayBuffer>
Examples

Export the modified PDF content

const operations = [
  {
    type: "rotatePages",
    pageIndexes: [0],
    rotateBy: 90
  }
];
instance.exportPDFWithOperations(operations).then(function (buffer) {
  buffer; // => ArrayBuffer
});

Download the modified PDF by using an `<a>` tag

const operations = [
  {
    type: "rotatePages",
    pageIndexes: [0],
    rotateBy: 90
  }
];
instance.exportPDFWithOperations(operations).then(function(buffer) {
  const supportsDownloadAttribute = HTMLAnchorElement.prototype.hasOwnProperty(
    "download"
  );
  const blob = new Blob([buffer], { type: "application/pdf" });
  if (navigator.msSaveOrOpenBlob) {
    navigator.msSaveOrOpenBlob(blob, "download.pdf");
  } else if (!supportsDownloadAttribute) {
    const reader = new FileReader();
    reader.onloadend = function() {
      const dataUrl = reader.result;
      downloadPdf(dataUrl);
    };
    reader.readAsDataURL(blob);
  } else {
    const objectUrl = window.URL.createObjectURL(blob);
    downloadPdf(objectUrl);
    window.URL.revokeObjectURL(objectUrl);
  }
});
function downloadPdf(blob) {
  const a = document.createElement("a");
  a.href = blob;
  a.style.display = "none";
  a.download = "download.pdf";
  a.setAttribute("download", "download.pdf");
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

exportXFDF(ignorePageRotation) → {Promise.<string>}

XFDF can be used to instantiate a viewer with a diff that is applied to the raw PDF. This format can be used to store annotation and form field value changes on your server and conveniently instantiate the viewer with the same content at a later time.

Instead of storing the updated PDF, this serialization only contains a diff that is applied on top of the existing PDF and thus allows you to cache the PDF and avoid transferring a potentially large PDF all the time.

This method is used to export the current annotations as XFDF. Use PSPDFKit.Configuration#XFDF to load it.

For Server-Backed setups, only saved annotations will be exported.

Parameters:
Name Type Description
ignorePageRotation boolean

Optional flag to ignore page rotation when exporting XFDF, by default false. This means that the exported XFDF will contain the annotations in the same orientation as the page and if you import this XFDF using PSPDFKit.Configuration#XFDFIgnorePageRotation the annotations will be imported in the same orientation no matter the page rotation.

Returns:

XFDF as a plain text.

Type
Promise.<string>
Example
instance.exportXFDF().then(function (xmlString) {
  // Persist it to a server
  fetch("https://example.com/annotations", {
    "Content-Type": "application/vnd.adobe.xfdf",
    method: "POST",
    body: xmlString
  }).then(...);
});

getAnnotations(pageIndex) → {Promise.<PSPDFKit.Immutable.List.<AnnotationsUnion>>}

Returns a PSPDFKit.Immutable.List of PSPDFKit.Annotations for the given pageIndex.

The list contains an immutable snapshot of the currently available annotations in the UI for the page. This means, that the returned list could include invalid annotations. Think for example of the following workflow:

  1. The user creates a new text annotation on a page.
  2. Now, the users double clicks the annotation and removes the text. The annotation is now invalid since it does not have any text. But since the annotation is not yet deselected, we will keep it visible.
  3. Next, the user updates the color of the text by using the annotation toolbar. The annotation will still be invalid although a change occurred.
  4. At the end, the user decides to type more text and deselects the annotation again. The annotation is now valid.

When you want to keep a reference to the latest annotations, you can listen for PSPDFKit.Instance~AnnotationsChangeEvent, PSPDFKit.Instance~AnnotationsWillSaveEvent, or PSPDFKit.Instance~AnnotationsDidSaveEvent to update your reference.

If annotations for this page have not been loaded yet, the promise will resolve only after we have received all annotations.

Parameters:
Name Type Description
pageIndex number

The page index for the annotations you want. pageIndex is zero-based and has a maximum value of totalPageCount - 1

Returns:

Resolves to annotations for the given page.

Type
Promise.<PSPDFKit.Immutable.List.<AnnotationsUnion>>
Example
instance.getAnnotations(0).then(function (annotations) {
  annotations.forEach(annotation => {
    console.log(annotation.pageIndex);
  });

  // Filter annotations by type
  annotations.filter(annotation => {
    return annotation instanceof PSPDFKit.Annotations.InkAnnotation;
  })

  // Filter annotations at a specific point
  const pointInFirstPage = new PSPDFKit.Geometry.Point({ x: 20, y: 30 });
  const annotationsAtPointInPage = annotationsOnFirstPage.filter(annotation => {
    return annotation.boundingBox.isPointInside(pointInFirstPage);
  });

  // Get the number of currently loaded annotations
  const totalAnnotations = annotations.size;
})

getAnnotationsGroups() → (nullable) {PSPDFKit.Immutable.Map.<string, Record.<string, PSPDFKit.Immutable.Set.<ID>>>}

This function will return all annotations groups, if there are any annotations groups.

Returns:

annotations groups

Type
PSPDFKit.Immutable.Map.<string, Record.<string, PSPDFKit.Immutable.Set.<ID>>>

getAttachment(attachmentId) → {Promise.<?Blob>}

Fetches an attachment or an embedded file based on its ID.

Parameters:
Name Type Description
attachmentId string

The ID of the attachments or embedded files that should be fetched.

Throws:

Will throw an error when the file can not be read.

Type
PSPDFKit.Error
Returns:

A promise that resolves to the attachment data.

Type
Promise.<?Blob>
Example
PSPDFKit.load(configuration).then(function(instance) {
  instance.getAttachment("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad").then(function(image) {
    console.log(image);
  });
})

getBookmarks() → {Promise.<PSPDFKit.Immutable.List.<PSPDFKit.Bookmark>>}

Returns a PSPDFKit.Immutable.List of PSPDFKit.Bookmark for the current document.

The list contains an immutable snapshot of the currently available bookmarks in the UI for the page.

When you want to keep a reference to the latest bookmarks, you can listen for PSPDFKit.Instance~BookmarksChangeEvent, PSPDFKit.Instance~BookmarksWillSaveEvent, or PSPDFKit.Instance~BookmarksDidSaveEvent to update your reference.

Returns:

Resolves to bookmarks for the given page.

Type
Promise.<PSPDFKit.Immutable.List.<PSPDFKit.Bookmark>>
Example
instance.getBookmarks().then(function (bookmarks) {
  bookmarks.forEach(bookmark => {
    console.log(bookmark.name);
  });

  // Get the number of currently loaded bookmarks
  const totalBookmarks = bookmarks.size;
})

getComments() → {Promise.<PSPDFKit.Immutable.List.<PSPDFKit.Comment>>}

Returns a PSPDFKit.Immutable.List of PSPDFKit.Comment for the current document.

The list contains an immutable snapshot of the currently available comments in the UI.

When you want to keep a reference to the latest comments, you can listen for PSPDFKit.Instance~CommentsChangeEvent.

Returns:

Resolves to comments.

Type
Promise.<PSPDFKit.Immutable.List.<PSPDFKit.Comment>>
Example
instance.getComments().then(function (comments) {
  comments.forEach(comment => {
    console.log(comment.text);
  });

  // Get the number of currently loaded comments
  const totalComments = comments.size;
})

getDocumentOutline() → {Promise.<PSPDFKit.Immutable.List.<PSPDFKit.OutlineElement>>}

Returns the document outline (table of content).

Returns:

A promise that resolves to a PSPDFKit.Immutable.List of PSPDFKit.OutlineElement

Type
Promise.<PSPDFKit.Immutable.List.<PSPDFKit.OutlineElement>>

getDocumentPermissions() → {Promise.<Object.<string, boolean>>}

Returns the current PSPDFKit.DocumentPermissions of the document.

Returns:

A Promise resolving to an object containing the document permissions keys along with their status (true or false).

Type
Promise.<Object.<string, boolean>>
Example
const permissions = await instance.getDocumentPermissions();

getEmbeddedFiles() → {Promise.<PSPDFKit.Immutable.List.<PSPDFKit.EmbeddedFile>>}

Returns a list containing the information of all the embedded files in the PDF.

If you want to get the content of a particular embedded file, you can use PSPDFKit.Instance#getAttachment

const embeddedFiles = await instance.getEmbeddedFiles()

const fileContent = await instance.getAttachment(embeddedFiles.get(0).attachmentId)
Returns:

List of embedded files in the document with their individual information.

Type
Promise.<PSPDFKit.Immutable.List.<PSPDFKit.EmbeddedFile>>
Example
const embeddedFilesInfo = await instance.getEmbeddedFiles();

getFormFieldValues() → {object}

Returns a simplified object that contains all form fields currently loaded and maps to their values. This object can be used to serialize form field values.

Values can be of type null, string, or Array.<string>.

This method does not check if all the form fields have been loaded. If you want to make sure that the all the document's form field values are retrieved, you have to make sure that the form fields have been retrieved first.

Returns:

A simplified object that contains all form field values.

Type
object
Example
await instance.getFormFields()
const formFieldValues = instance.getFormFieldValues();
console.log(formFieldValues); // => { textField: 'Text Value', checkBoxField: ['A', 'B'], buttonField: null }

getFormFields() → {Promise.<PSPDFKit.Immutable.List.<PSPDFKit.FormFields.FormField>>}

Returns a PSPDFKit.Immutable.List of all PSPDFKit.FormFields for this document.

Returns:

Resolves to a list of all form fields.

Type
Promise.<PSPDFKit.Immutable.List.<PSPDFKit.FormFields.FormField>>
Example
instance.getFormFields().then(formFields => {
  formFields.forEach(formField => {
    console.log(formField.name);
  });

  // Filter form fields by type
  formFields.filter(formField => (
    formField instanceof PSPDFKit.FormFields.TextFormField
  ));

  // Get the total number of form fields
  const totalFormFields = formFields.size;
})

Returns a copy of the available stored signatures. Signatures are ink and image annotations and therefore can be converted to JavaScript objects with PSPDFKit.Annotations.toSerializableObject.

When the application doesn't have signatures in store this method will invoke PSPDFKit.Configuration#populateStoredSignatures to retrieve the initial list of annotations.

Deprecated
Returns:

Promise that resolves with an Immutable list of signatures

Type
Promise.<PSPDFKit.Immutable.List.<(PSPDFKit.Annotations.InkAnnotation|PSPDFKit.Annotations.ImageAnnotation)>>
Example

Retrieve the signatures and convert them to JSON

instance
  .getInkSignatures()
  .then(signatures => signatures.map(PSPDFKit.Annotations.toSerializableObject).toJS());

getLayers() → {Promise.<Array.<PSPDFKit.Layer>>}

Returns a list of OCG layers present in the document.

Returns:

A promise that resolves to an Array of PSPDFKit.Layer

Type
Promise.<Array.<PSPDFKit.Layer>>

getLayersVisibilityState() → {Promise.<PSPDFKit.LayersVisibilityState>}

Returns the current OCG layers visibility state.

OCG layers are groups of content in the document, that can be shown or hidden independently.

This method returns the current visibility state of the layers in the document as an object with a visibleLayerIds Array that contains the list of layers identified by their ocgId number, which are currently visible.

Returns:

A promise that resolves to a PSPDFKit.LayersVisibilityState

Type
Promise.<PSPDFKit.LayersVisibilityState>
Example
instance.getLayersVisibilityState().then(function (layersVisibilityState) {
 console.log(layersVisibilityState); // => { visibleLayerIds: [1, 2, 3] }
});

getMarkupAnnotationText(annotation) → {Promise.<string>}

Extracts the text behind a PSPDFKit.Annotations.MarkupAnnotation. This can be useful to get the highlighted text.

Warning: This is only an approximation. Highlighted text might not always 100% represent the text, as we just look behind the absolute coordinates to see what text is beneath. PDF highlight annotations are not markers in the content itself.

Parameters:
Name Type Description
annotation PSPDFKit.Annotations.MarkupAnnotation

The text markup annotation you want to extract the text behind.

Returns:

The text behind the annotation.

Type
Promise.<string>
Example

Get the text of all text markup annotations on the first page:

const annotations = await instance.getAnnotations(0);
const markupAnnotations = annotations.filter(
  annotation => annotation instanceof PSPDFKit.Annotations.MarkupAnnotation
);
const text = await Promise.all(
  markupAnnotations.map(instance.getMarkupAnnotationText)
);
console.log(text);

getOverlappingAnnotations(annotationOrFormField) → {Promise.<PSPDFKit.Immutable.List.<AnnotationsUnion>>}

Returns a PSPDFKit.Immutable.List of PSPDFKit.Annotations for the given form field or annotation.

The list contains an immutable snapshot of the currently overlapping annotations for the argument.

If annotations for this page have not been loaded yet, the promise will resolve only after we have received all annotations.

Parameters:
Name Type Description
annotationOrFormField AnnotationsUnion | FormField

the annotation or the form field that needs to be checked for overlapping annotations.

Returns:

Resolves to a list of the annotations that overlap the given argument.

Type
Promise.<PSPDFKit.Immutable.List.<AnnotationsUnion>>
Examples
get signature overlapping a signature form field

// The name of the field you want to check.
const formFieldName = "signature";

// First get all `FormFields` in the `Document`.
const formFields = await instance.getFormFields();

// Get a signature form with the specific name you want.
const field = formFields.find(
 (formField) =>
  formField.name === formFieldName && formField instanceof PSPDFKit.FormFields.SignatureFormField
 );

// Check if the signature form field has been signed
await instance.getOverlappingAnnotations(field);
// It will result in a list of annotations that overlaps the given signature form field.
// If no annotation overlaps the form field, the list will be empty.
get annotations overlapping an ink annotation

const annotations = instance.getAnnotations(0);
const inkAnnotation = annotations.find(
 (annotation) =>
  annotation instanceof PSPDFKit.Annotation.InkAnnotation
);
await instance.getOverlappingAnnotations(inkAnnotation);
// It will result in a list of annotations that overlaps the given signature form field.
// If no annotation overlaps the form field, the list will be empty.

getPageTabOrder(pageIndex) → {Promise.<Array.<string>>}

*** Standalone only ***

This method is used to retrieve the tab order of annotations in a given page.

The tab order will be returned as an array of annotation IDs.

In the case of widget annotations associated to a radio form field, all the widgets associated to the same form field are rendered next to the first one found in the provided Array of annotation IDs.

Parameters:
Name Type Description
pageIndex number
Throws:

Will throw an error when the supplied page index is not a number.

Type
PSPDFKit.Error
Returns:

A promise that resolves to an ordered array of annotation IDs.

Type
Promise.<Array.<string>>
Example

Get the tab order of annotations in page 0

instance.getPageTabOrder(0);

getSelectedAnnotations() → (nullable) {PSPDFKit.Immutable.List.<AnnotationsUnion>}

If multiple annotations are selected, this function will return the set of selected annotations.

Returns:

annotation

Type
PSPDFKit.Immutable.List.<AnnotationsUnion>

getSignaturesInfo() → {Promise.<PSPDFKit.SignaturesInfo>}

Gets the digital signatures validation information for all the signatures present in the current document. See PSPDFKit.SignaturesInfo.

Returns:

Promise that resolves with a PSPDFKit.SignaturesInfo.

Type
Promise.<PSPDFKit.SignaturesInfo>
Example

Retrieve signatures information

instance.getSignaturesInfo()
  .then(signaturesInfo => {
    console.log(signaturesInfo.status)
    if(signaturesInfo.signatures) {
      const invalidSignatures = signaturesInfo.signatures
        .filter(signature => signature.signatureValidationStatus !== PSPDFKit.SignatureValidationStatus.valid);
      console.log(invalidSignatures);
    }
});

Additional information can be found in
this guide article.

Returns a copy of the available stored signatures. Signatures are ink and image annotations and therefore can be converted to JavaScript objects with PSPDFKit.Annotations.toSerializableObject.

When the application doesn't have signatures in store this method will invoke PSPDFKit.Configuration#populateStoredSignatures to retrieve the initial list of annotations.

Returns:

Promise that resolves with an Immutable list of signatures

Type
Promise.<PSPDFKit.Immutable.List.<(PSPDFKit.Annotations.InkAnnotation|PSPDFKit.Annotations.ImageAnnotation)>>
Example

Retrieve the signatures and convert them to JSON

instance
  .getStoredSignatures()
  .then(signatures => signatures.map(PSPDFKit.Annotations.toSerializableObject).toJS());

getTextFromRects(pageIndex, rects) → {Promise.<string>}

Given a list of rects and their page index, extracts the text intersecting them. This can be useful to get the text that overlaps a focused annotation to give more context to screen reader users.

Warning: The computed text might be partial as we just look behind the absolute coordinates of a rect to see what text it is intersecting.

Parameters:
Name Type Description
pageIndex number

the page index where the rects are located

rects PSPDFKit.Immutable.List.<PSPDFKit.Geometry.Rect>

An immutable list of rects

Returns:

The text that intersect the rects.

Type
Promise.<string>
Example

Get the text of all ink annotations on the first page:

const annotations = await instance.getAnnotations(0);
const inkAnnotationsRects = annotations.filter(
  annotation => annotation instanceof PSPDFKit.Annotations.InkAnnotation
).map(annotation => annotation.boundingBox);
const text = await instance.getTextFromRects(0, inkAnnotationsRects);
console.log(text);

getTextSelection() → {Promise.<?PSPDFKit.TextSelection>}

Gets the current text selection in the document, if any.

Returns:

A promise that resolves to the current text selection, or null if no text is selected.

Type
Promise.<?PSPDFKit.TextSelection>
Example

Get the text selection as a string

const currentSelection = instance.getTextSelection();
if (currentSelection != null) {
  const text = await currentSelection.getText();
  alert(`Selection: '${text}'`);
}

groupAnnotations(annotationsOrAnnotationsIdnullable)

Group annotations in the user interface.

Parameters:
Name Type Attributes Description
annotationsOrAnnotationsId PSPDFKit.Immutable.List.<(PSPDFKit.Annotations.Annotation|string)> <nullable>

The annotations model or annotations IDs you want to be grouped. Annotations selected for grouping must be on the same page. Annotations that are already grouped will be removed from the previous group and added to the new one.

hasUnsavedChanges() → {boolean}

Returns true if any local changes are not yet saved. This can be used in combination with PSPDFKit.Configuration.autoSaveMode to implement fine grained save controls.

Whenever changes are saved (for example, when calling PSPDFKit.Instance#save), the method will return false again.

Returns:

Whether unsaved changes are present or not.

Type
boolean
Example
PSPDFKit.load(configuration).then(function(instance) {
  instance.hasUnsavedChanges(); // => false
});

jumpAndZoomToRect(pageIndex, rect)

Brings the rect (in PDF page coordinates) into the viewport. This function will also change the zoom level so that the rect is visible completely in the best way possible.

Parameters:
Name Type Description
pageIndex number

The index of the page you want to have information about. If none is provided, the first page (pageIndex 0) will be used.

rect PSPDFKit.Geometry.Rect

The rect in PDF page coordinates that you want to jump to.

Throws:

Will throw an error when the supplied arguments are not valid.

Type
PSPDFKit.Error
Example

Jump and zoom to the ink annotation

instance.jumpAndZoomToRect(inkAnnotation.pageIndex, inkAnnotation.boundingBox);

jumpToRect(pageIndex, rect)

Brings the rect (in PDF page coordinates) into the viewport. This function will not change the zoom level.

This can be used to scroll to specific annotations or search results.

Parameters:
Name Type Description
pageIndex number

The index of the page you want to have information about. If none is provided, the first page (pageIndex 0) will be used.

rect PSPDFKit.Geometry.Rect

The rect in PDF page coordinates that you want to jump to.

Throws:

Will throw an error when the supplied arguments is not valid.

Type
PSPDFKit.Error
Example

Jump to the ink annotation

instance.jumpToRect(inkAnnotation.pageIndex, inkAnnotation.boundingBox);

pageInfoForIndex(pageIndex) → (nullable) {PSPDFKit.PageInfo}

Get the PageInfo for the specified pageIndex. If there is no page at the given index, it will return null.

Parameters:
Name Type Description
pageIndex number

The index of the page you want to have information about

Returns:

The PageInfo or null.

Type
PSPDFKit.PageInfo

print(options)

Print the document programmatically.

Parameters:
Name Type Description
options object

Print options object:

Throws:

This method will throw when printing is disabled, currently in process or when an invalid PSPDFKit.PrintMode was supplied.

Type
PSPDFKit.Error

removeCustomOverlayItem(id)

This method is used to remove an existing PSPDFKit.CustomOverlayItem.

Parameters:
Name Type Description
id string

The id of the item to remove.

Example

Create and then remove a text node.

const id = "1";
const item = new PSPDFKit.CustomOverlayItem({
 id: id,
 node: document.createTextNode("Hello from PSPDFKit for Web."),
 pageIndex: 0,
 position: new PSPDFKit.Geometry.Point({ x: 100, y: 200 }),
});
instance.setCustomOverlayItem(item);

instance.removeCustomOverlayItem(id);

removeEventListener(action, listener)

This method can be used to remove an event listener registered via PSPDFKit.Instance#addEventListener.

It requires the same reference to the function that was used when registering the function (equality will be verified the same way as it is in the DOM API).

Parameters:
Name Type Description
action string

The action you want to add an event listener to. See the list on PSPDFKit.Instance#addEventListener for possible event types.

listener function

A listener function.

Throws:

Will throw an error when the supplied event is not valid.

Type
PSPDFKit.Error
Examples

Proper approach - Use the same reference for registering and removing

const callback = someFunction.bind(this)
instance.addEventListener("viewState.zoom.change", callback);
instance.removeEventListener("viewState.zoom.change", callback);

Wrong approach - Creates two different functions

instance.addEventListener("viewState.zoom.change", someFunction.bind(this));
// This will not work because `Function#bind()` will create a new function!
instance.removeEventListener("viewState.zoom.change", someFunction.bind(this));

renderPageAsArrayBuffer(dimension, pageIndex) → {Promise.<ArrayBuffer>}
Standalone Only

Provided a dimension and pageIndex renders a page of a document and returns the result as ArrayBuffer. This can be used as thumbnail.

You can specify a width or height (but not both at the same time) as the first dimension argument, each accepts a value in the interval (0; 5000]. The other dimension will be calculated based on the aspect ratio of the document.

This method can be used to provide thumbnail images for your document list. You can use it in a <canvas> tag. The following example will load the cover of the loaded document with a width of 400px. We set the width of the <canvas> tag to 200px, so the image will be sharp on high DPI screens.

Parameters:
Name Type Description
dimension

The size of the resulting image. Only accepts either width or height, but not both. The other dimension will be calculated accordingly.

Properties
Name Type Description
width number

The width of the resulting image.

height number

The height of the resulting image.

pageIndex number

The index of the page you want to have information about.

Returns:

The raw image as bitmap.

Type
Promise.<ArrayBuffer>
Example
const pageWidth = instance.pageInfoForIndex(0).width;
const pageHeight = instance.pageInfoForIndex(0).height;

const width = 400;
const height = Math.round(width * pageHeight / pageWidth);

instance.renderPageAsArrayBuffer({ width }, 0).then(function(buffer) {
  const canvas = document.createElement('canvas');
  canvas.width = width;
  canvas.height = height;

  canvas.style.transformOrigin = "0 0";
  canvas.style.transform = "scale(0.5)";

  const imageView = new Uint8Array(buffer);
  const ctx = canvas.getContext("2d");
  const imageData = ctx.createImageData(width, height);
  imageData.data.set(imageView);
  ctx.putImageData(imageData, 0, 0);

  document.body.appendChild(canvas);
});

renderPageAsImageURL(dimension, pageIndex) → {Promise.<string>}

Generates a URL to an image for the first page of a document or the page of the provided pageIndex. This can be used as thumbnail.

You can specify a width or height (but not both at the same time) as the first dimension argument, each accepts a value in the interval (0; 5000]. The other dimension will be calculated based on the aspect ratio of the document.

This endpoint can be used to provide thumbnail images for your document list. You can use it as a src for an img tag. The following example will load the cover of the loaded document with a width of 400px.

The returned URL is a Blob URL.

In order to prevent memory leaks, it's recommended to revoke the returned object URL once the image is no longer needed, as in the example.

Parameters:
Name Type Description
dimension

The size of the resulting image. Only accepts either width or height, but not both. The other dimension will be calculated accordingly.

Properties
Name Type Description
width number

The width of the resulting image.

height number

The height of the resulting image.

pageIndex number

The index of the page you want to have information about.

Returns:

The image url.

Type
Promise.<string>
Example
let objectURL
instance.renderPageAsImageURL({ width: 400 }, 0).then(function(src) {
  const image = document.createElement('img');
  image.src = src;
  objectURL = src;
  document.body.appendChild(image);
});
// Once the image is no longer needed, we revoke the URL so that the associated
// Blob is released.
function callWhenTheImageIsNoLongerNeeded() {
  // Is it an object URL?
  if (objectURL.split("://")[0] === "blob") {
    URL.revokeObjectURL(objectURL);
  }
}

resetGroup()

This method can be used to change the default group back to original after it was changed to something else using instance.setGroup.

This method is no-op if Collaboration Permissions is not enabled.

save() → {Promise.<void>}

With PSPDFKit.AutoSaveMode it's possible to define when local changes get saved, but it's also possible to define the point to save changes yourself.

By choosing PSPDFKit.AutoSaveMode.DISABLED, nothing gets saved automatically, but by calling save, it's possible to manually trigger save. This can be useful when you want to have full control when new changes get saved to your backend.

Returns:

Promise that resolves once all changes are saved on remote server (in case of server-based backend) or in local backend (in case of standalone). If changes could not be saved, rejects with PSPDFKit.SaveError.

Type
Promise.<void>
Example
PSPDFKit.load(configuration).then(async (instance) => {
  const annotation = new PSPDFKit.Annotations.InkAnnotation({
    pageIndex: 0,
    lines: PSPDFKit.Immutable.List([
      PSPDFKit.Immutable.List([
        new PSPDFKit.Geometry.DrawingPoint({ x: 0,   y: 0  }),
        new PSPDFKit.Geometry.DrawingPoint({ x: 100, y: 100}),
      ])
    ])
  });

 await instance.create(annotation);

 await instance.save(); // Now the annotation gets saved.
})

Queries the PDF backend for all search results of a given term. Search is case-insensitive and accented letters are ignored. The minimum query length for the term query to be performed can be retrieved from PSPDFKit.Instance#minQueryLength.

Shorter queries will throw an error.

Parameters:
Name Type Description
term string

The search term.

options

Optional parameters used for search operation.

Properties
Name Type Description
startPageIndex number

The page index to start searching from. options.endPageIndex must be provided if this parameter is given.

endPageIndex number

The last page index to search (inclusive). options.startPageIndex must be provided if this parameter is given.

searchType PSPDFKit.SearchType

The search type which describes whether the query is a text, pattern or regex. Default is PSPDFKit.SearchType.TEXT.

searchInAnnotations boolean

Whether you want to search in annotations. Default is false.

caseSensitive boolean

Whether you want the search to be case-sensitive. Default is false if searchType is PSPDFKit.SearchType.TEXT and true for other types of searches.

Returns:

Resolves to an immutable list of search results.

Type
Promise.<PSPDFKit.Immutable.List.<PSPDFKit.SearchResult>>
Examples

Search for all occurrences of `foo`

instance.search("foo").then(results => {
  console.log(results.size);
});

Search within a page range.

instance.search("foo", { startPageIndex: 1, endPageIndex: 4 }).then(results => {
  console.log(results.size);
});

Search for a regex.

instance.search("Q[a-z]+ck\\sC.*[tT]", { searchType: PSPDFKit.SearchType.REGEX }).then(results => {
  console.log(results.size);
});

Search for all date patterns on the pages.

instance.search(PSPDFKit.SearchPattern.DATE, { searchType: PSPDFKit.SearchType.PATTERN }).then(results => {
  console.log(results.size);
});

Search for a regex in a case-insensitive way.

instance.search("he[a-z]+", { searchType: PSPDFKit.SearchType.REGEX, caseSensitive: false }).then(results => {
  console.log(results.size);
});

setAnnotationCreatorName(annotationCreatorNamenullable)

Sets the annotation creator name. Each created annotation will have the creators name set in the author property.

Parameters:
Name Type Attributes Description
annotationCreatorName string <nullable>

setAnnotationPresets(stateOrFunction)

This method is used to update the annotation presets.

It makes it possible to add new annotation presets and edit or remove existing ones.

When you pass in an object with keyed PSPDFKit.AnnotationPreset, the current annotation presets will be immediately updated. Calling this method is also idempotent.

If you pass in a function, it will be immediately invoked and will receive the current {string: <PSPDFKit.AnnotationPreset>} object as argument. You can use this to modify the object based on its current value. This type of update is guaranteed to be atomic - the value of currentAnnotationPresets can't change in between. See: AnnotationPresetsSetter

When one of the supplied PSPDFKit.AnnotationPreset is invalid, this method will throw an PSPDFKit.Error that contains a detailed error message.

Since annotationPresets is a regular JavaScript object, it can be manipulated using standard Object methods.

Parameters:
Name Type Description
stateOrFunction Object.<string, PSPDFKit.AnnotationPreset> | PSPDFKit.Instance~AnnotationPresetsSetter

Either a new AnnotationPresets object which would overwrite the existing one, or a callback that will get invoked with the current annotation presets and is expected to return the new annotation presets object.

Throws:

Will throw an error when the supplied annotation preset object is not valid.

Type
PSPDFKit.Error
Examples

The new changes will be applied immediately

instance.setAnnotationPresets(newAnnotationPresets);
instance.annotationPresets === newAnnotationPresets; // => true

Adding an annotation preset for an ellipse annotation variant.

const myAnnotationPreset = {
  dashedEllipse: {
    strokeDashArray: [3, 3],
  }
}
instance.setAnnotationPresets(annotationPresets => ({ ...annotationPresets, myAnnotationPreset })

setAnnotationToolbarItems(annotationToolbarItemsCallback)

You can use this callback to set/modify the toolbar items present in the annotation toolbar after the document has loaded.

The callback will receive the annotation which is being created or selected and based on it, you can have different annotation toolbars for different annotations.

You can do the following modifications using this API:

  • Add new annotation toolbar items
  • Remove existing annotation toolbar items
  • Change the order of the existing annotation toolbar items
  • Modify selected properties of the annotation toolbar items

You can also use the hasDesktopLayout to determine if the current UI is being rendered on mobile or desktop. Based on that, you can implement different designs for Desktop and Mobile.

This callback gets called every time the annotation toolbar is mounted.

Parameters:
Name Type Description
annotationToolbarItemsCallback PSPDFKit.AnnotationToolbarItemsCallback
Example

Add a new annotation toolbar item

instance.setAnnotationToolbarItems((annotation, { defaultAnnotationToolbarItems, hasDesktopLayout }) => {
    const node = document.createElement('node')
    node.innerText = "Custom Item"

    const icon = `<svg xmlns="http://www.w3.org/2000/svg" height="24" width="24" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4" /></svg>`

    return [{
      id: "custom",
      type: "custom",
      node: node,
      icon: icon,
      className: 'Custom-Node',
      onPress: () => alert("Custom item pressed!")
    }, ...defaultAnnotationToolbarItems];
  });

setCurrentAnnotationPreset(AnnotationPresetIDnullable)

This method is used to set the current active annotation preset.

It makes it possible to specify what annotation preset should be used when new annotations are created in the UI by passing the annotation preset key string as argument.

The current annotation preset is set when the toolbar annotation buttons are used to create annotations. This method allows to set the current annotation preset programmatically, as well as resetting it by passing null as argument.

When the supplied key does not correspond with an existing PSPDFKit.AnnotationPreset, this method will throw an PSPDFKit.Error that contains a detailed error message.

Parameters:
Name Type Attributes Description
AnnotationPresetID string <nullable>

Annotation preset name.

Throws:

Will throw an error when the supplied annotation preset key does not exist.

Type
PSPDFKit.Error
Examples

The new changes will be applied immediately

instance.setCurrentAnnotationPreset("ink");
instance.currentAnnotationPreset === "ink"; // => true

Setting an annotation preset for a closed arrow line annotation.

instance.setAnnotationPresets(annotationPresets => {
  return {
    ...annotationPresets,
    line: {
      ...annotationPresets.line,
      lineCaps: {
        end: "closedArrow"
      }
    }
  }
});
instance.setCurrentAnnotationPreset("line");
instance.setViewState(viewState =>
  viewState.set("interactionMode", PSPDFKit.InteractionMode.SHAPE_LINE),
);

setCustomOverlayItem(item)

This method is used to set a new PSPDFKit.CustomOverlayItem or update an existing one.

Parameters:
Name Type Description
item PSPDFKit.CustomOverlayItem

The item to create or update.

Examples

Add a text node to the first page.

let item = new PSPDFKit.CustomOverlayItem({
 id: "1",
 node: document.createTextNode("Hello from PSPDFKit for Web."),
 pageIndex: 0,
 position: new PSPDFKit.Geometry.Point({ x: 100, y: 200 }),
});
instance.setCustomOverlayItem(item);

Update a text node.

item = item.set("node", document.createTextNode("Hello again my friend!!!"));
instance.setCustomOverlayItem(item);

setCustomRenderers(customRenderers)

Sets the current custom renderers. When this function is called with a new PSPDFKit.CustomRenderers object, all visible custom rendered annotations are immediately updated.

Parameters:
Name Type Description
customRenderers PSPDFKit.CustomRenderers

setCustomUIConfiguration(customUIConfigurationOrCustomUIConfigurationSetter)

Sets the current custom UI configuration. When this function is called with a new PSPDFKit.CustomUI object, all visible sidebars are immediately updated.

Parameters:
Name Type Description
customUIConfigurationOrCustomUIConfigurationSetter PSPDFKit.CustomUIConfiguration | PSPDFKit.Instance~CustomUIConfigurationSetter

setDocumentComparisonMode(documentComparisonConfiguration) → {Promise.<void>}

Standalone only

Enables or disables the document comparison UI.

When a PSPDFKit.DocumentComparisonConfiguration object is passed, the document comparison UI is mounted and initialized with the provided settings.

When null is passed, the document comparison UI is hidden if it was being shown.

Parameters:
Name Type Description
documentComparisonConfiguration PSPDFKit.DocumentComparisonConfiguration | null

Initial document comparison configuration.

Returns:
Type
Promise.<void>
Example

Initialize and show the document comparison UI

instance.setDocumentComparisonMode({
  documentA: {
    source: fetch("old-document.pdf").then(res => res.arrayBuffer())
  },
  documentB: {
    source: fetch("old-document.pdf").then(res => res.arrayBuffer())
  },
  autoCompare: true
});

setDocumentEditorFooterItems(documentEditorFooterItemsOrFunction)

This method is used to update the document editor footer of the PDF editor. It makes it possible to add new items and edit or remove existing ones.

When you pass in an array of PSPDFKit.DocumentEditorFooterItem, the current items will be immediately updated. Calling this method is also idempotent.

If you pass in a function, it will be immediately invoked and will receive the current array of PSPDFKit.DocumentEditorFooterItem as argument. You can use this to modify the list based on its current value. This type of update is guaranteed to be atomic - the value of currentDocumentEditorFooterItems can't change in between. See: DocumentEditorFooterItemsSetter

When one of the supplied PSPDFKit.DocumentEditorFooterItem is invalid, this method will throw an PSPDFKit.Error that contains a detailed error message.

Since items is a regular JavaScript Array of object literals it can be manipulated using standard array methods like forEach, map, reduce, splice and so on. Additionally you can use any 3rd party library for array manipulation like lodash or just.

Parameters:
Name Type Description
documentEditorFooterItemsOrFunction Array.<PSPDFKit.DocumentEditorFooterItem> | PSPDFKit.Instance~DocumentEditorFooterItemsSetter

Either a new array of DocumentEditorFooterItem which would overwrite the existing one, or a callback that will get invoked with the current footer items and is expected to return the new array of items.

Throws:

will throw an error when the supplied items array is not valid. This will also throw an error if you don not have document editor license.

Type
PSPDFKit.Error
Examples

Use ES2015 arrow functions and the update callback to reduce boilerplate

instance.setDocumentEditorFooterItems(items => items.reverse());

The new changes will be applied immediately

instance.setDocumentEditorFooterItems(newItems);
instance.documentEditorFooterItems === newItems; // => true

Changing a property of a custom button

const myButton = {
  type: "custom",
  id: "my-button",
  onPress() {
    alert("test");
  },
};

setDocumentEditorToolbarItems(documentEditorToolbarItemsOrFunction)

This method is used to update the document editor toolbar of the PDF editor. It makes it possible to add new items and edit or remove existing ones.

When you pass in an array of PSPDFKit.DocumentEditorToolbarItem, the current items will be immediately updated. Calling this method is also idempotent.

If you pass in a function, it will be immediately invoked and will receive the current array of PSPDFKit.DocumentEditorToolbarItem as argument. You can use this to modify the list based on its current value. This type of update is guaranteed to be atomic - the value of currentDocumentEditorToolbarItems can't change in between. See: DocumentEditorToolbarItemsSetter

When one of the supplied PSPDFKit.DocumentEditorToolbarItem is invalid, this method will throw an PSPDFKit.Error that contains a detailed error message.

Since items is a regular JavaScript Array of object literals it can be manipulated using standard array methods like forEach, map, reduce, splice and so on. Additionally you can use any 3rd party library for array manipulation like lodash or just.

Parameters:
Name Type Description
documentEditorToolbarItemsOrFunction Array.<PSPDFKit.DocumentEditorToolbarItem> | PSPDFKit.Instance~DocumentEditorToolbarItemsSetter

Either a new array of DocumentEditorToolbarItem which would overwrite the existing one, or a callback that will get invoked with the current toolbar items and is expected to return the new array of items.

Throws:

will throw an error when the supplied items array is not valid. This will also throw an error if you don not have document editor license.

Type
PSPDFKit.Error
Examples

Use ES2015 arrow functions and the update callback to reduce boilerplate

instance.setDocumentEditorToolbarItems(items => items.reverse());

The new changes will be applied immediately

instance.setDocumentEditorToolbarItems(newItems);
instance.documentEditorToolbarItems === newItems; // => true

Changing a property of a custom button

const myButton = {
  type: "custom",
  id: "my-button",
  onPress() {
    alert("test");
  },
};

setDocumentOutline(outline) → {Promise.<void>}

Standalone only

Sets the document outline (table of content).

Parameters:
Name Type Description
outline PSPDFKit.Immutable.List.<PSPDFKit.OutlineElement>

The outline to set.

Returns:

A promise that resolves when the outline has been set.

Type
Promise.<void>

setEditableAnnotationTypes(editableAnnotationTypes)

This method is used to update the editable annotation types.

When one of the supplied PSPDFKit.Annotations.Annotation is invalid, this method will throw an PSPDFKit.Error that contains a detailed error message.

Parameters:
Name Type Description
editableAnnotationTypes Array.<AnnotationsUnion>
Throws:

Will throw an error when the supplied array is not valid.

Type
PSPDFKit.Error
Example

Only allow editing ink annotations

instance.setEditableAnnotationTypes([PSPDFKit.Annotations.InkAnnotation]);
instance.editableAnnotationTypes === [PSPDFKit.Annotations.InkAnnotation]; // => true

setEditingAnnotation(annotationOrAnnotationIdnullable, autoSelectTextnullable)

Selects an annotation in the user interface and enters edit mode. If annotationOrAnnotationId is empty, the current selection will be cleared instead.

This method works with PSPDFKit.Annotations.TextAnnotation and PSPDFKit.Annotations.NoteAnnotation. When called with other annotation types that don't have any text it will simply select the annotation.

Parameters:
Name Type Attributes Description
annotationOrAnnotationId AnnotationsUnion | string <nullable>

The annotation model or annotation ID you want to set as selected. If null is used, the current selection will be cleared instead.

autoSelectText boolean <nullable>

Whether the text should be automatically selected.

setFormFieldValues(formFieldValues) → {Promise.<void>}

Updates the values of form fields. It's possible to update multiple form fields at once.

The object must use the PSPDFKit.FormFields.FormField#name as a key and the values must be of type null, string, or Array.<string>. A null value will reset the form field to either null, or its default value if available.

This method returns a Promise that resolves when all the form fields have been updated, so it should be awaited whenever you need to get or modify form fields immediately to ensure the form field value is synchronized.

Parameters:
Name Type Description
formFieldValues object

An object that contains the form field names that should be updated as keys and their value as values.

Returns:

Resolves when the values have been set.

Type
Promise.<void>
Example
instance.setFormFieldValues({
  textField: "New Value",
  checkBoxField: ["B", "C"],
});

setGroup(group)

This method is used to update the group that will be used by default in all the newly created form-fields, comments and annotations. If you don't have permission to change the group, you will get error when you try to add an annotation, comment or form-field.

This method is no-op if Collaboration Permissions is not enabled.

Parameters:
Name Type Description
group string

The new group that you want to use for all the newly created form-fields, comments and annotations.

setInkSignatures(StoredSignaturesOrFunction)

This method is used to update the signatures list. It makes it possible to add new signatures and edit or remove existing ones.

Ink Signatures are Ink Annotations whose pageIndex and boundingBox is calculated at creation time. When selected via UI such annotations are used as template to create new PSPDFKit.Annotations.InkAnnotations and PSPDFKit.Annotations.ImageAnnotations. . When you pass in a List of PSPDFKit.Annotations.InkAnnotation and PSPDFKit.Annotations.ImageAnnotation, the current list of signatures will be immediately updated. Calling this method is also idempotent.

If you pass in a function, it will be invoked with the current List of PSPDFKit.Annotations.InkAnnotation and PSPDFKit.Annotations.ImageAnnotation as argument. You can use this to modify the list based on its current value. This type of update is guaranteed to be atomic - the value of getStoredSignatures() can't change in between. See: StoredSignaturesSetter

When the application doesn't have signatures in store this method will invoke PSPDFKit.Configuration#populateStoredSignatures to retrieve the initial list of annotations and it will pass it to your function.

When the list is invalid, this method will throw an PSPDFKit.Error that contains a detailed error message.

Parameters:
Name Type Description
StoredSignaturesOrFunction Array.<PSPDFKit.ToolbarItem> | PSPDFKit.Instance~StoredSignaturesSetter

Either a new array of signatures which would overwrite the existing one, or a callback that will get invoked with the current toolbar items and is expected to return the new array of items.

Deprecated
Throws:

Will throw an error when the supplied items array is not valid.

Type
PSPDFKit.Error
Examples

Fetch and set a list of signatures

const signatures = fetch("/signatures")
  .then(r => r.json())
  .then(a => (
      new PSPDFKit.Immutable.List(
         a.map(PSPDFKit.Annotations.fromSerializableObject)
      )
    )
  );
signatures.then(signatures => { instance.setInkSignatures(signatures) });

Use ES2015 arrow functions and the update callback to reduce boilerplate

instance.setInkSignatures(signatures => signatures.reverse());

Add a Ink Signature to the existing list

const signature = new PSPDFKit.Annotations.InkAnnotation({ lines: ..., boundingBox: ... });

instance.setInkSignatures(signatures => signatures.push(signature));

Remove the first Ink Signature from the list

instance.setInkSignatures(signatures => signatures.shift());

setIsEditableAnnotation(isEditableAnnotationCallback)

This method is used to update the isEditableAnnotation callback

When the supplied callback is invalid it will throw a PSPDFKit.Error that contains a detailed error message.

Parameters:
Name Type Description
isEditableAnnotationCallback PSPDFKit.IsEditableAnnotationCallback
Throws:

Will throw an error when the supplied array is not valid.

Type
PSPDFKit.Error
Example

Only allow editing annotations from a specific creator name

instance.setIsEditableAnnotation((annotation) => annotation.creatorName === "Alice");

setIsEditableComment(isEditableCommentCallback)

This method is used to update the isEditableComment callback

When the supplied callback is invalid it will throw a PSPDFKit.Error that contains a detailed error message.

To learn more check this guide article.

Parameters:
Name Type Description
isEditableCommentCallback PSPDFKit.IsEditableCommentCallback
Throws:

Will throw an error when the supplied array is not valid.

Type
PSPDFKit.Error
Example

Only allow editing comments from a specific creator name

instance.setIsEditableComment((comment) => comment.creatorName === myCurrentUser.name);

setLayersVisibilityState(layersVisibilityState) → {Promise.<void>}

Sets the OCG visibility state.

This method takes an PSPDFKit.LayersVisibilityState object as an argument, which contains a visibleLayerIds Array that contains the list of layers identified by their ocgId, and makes them visible, hiding any other layers not included in the Array.

Parameters:
Name Type Description
layersVisibilityState PSPDFKit.LayersVisibilityState

The OCG visibility state to set.

Returns:

A promise that resolves when the OCG visibility state has been set.

Type
Promise.<void>
Example
instance.setLayersVisibilityState({
  visibleLayerIds: [1, 2, 3]
})

setLocale(locale) → {Promise}

Sets the locale for the application. When setting a locale that doesn't exist it tries to fall back to the parent locale when available. For example en-US falls back to en.

See PSPDFKit.I18n.locales to get a list of all the available locales.

Parameters:
Name Type Description
locale string

The locale to set the app to. It must be one of PSPDFKit.I18n.locales.

Throws:

Will throw an error when the locale does not exist.

Type
PSPDFKit.Error
Returns:

void Returns a promise that resolves once the locale is set.

Type
Promise

setMaxMentionSuggestions(maxMentionSuggestions)

Server only Set the maximum number of suggestions that will be shown when mentioning a user.

Parameters:
Name Type Description
maxMentionSuggestions number

The maximum number of suggestions that will be shown when mentioning a user.

Example
instance.setMaxMentionSuggestions(5);

setMeasurementPrecision(precision)

Set the precision value of all the newly created measurement annotations.

Parameters:
Name Type Description
precision PSPDFKit.MeasurementPrecision

Precision value

Example
instance.setMeasurementPrecision(PSPDFKit.MeasurementPrecision.THREE);

setMeasurementScale(scale)

Set the default value of scale for all newly created measurement annotations.

Parameters:
Name Type Description
scale PSPDFKit.MeasurementScale

Scale value

Example
instance.setMeasurementScale(new PSPDFKit.MeasurementScale({
  unitFrom: PSPDFKit.MeasurementScaleUnitFrom.CENTIMETERS,
  unitTo: PSPDFKit.MeasurementScaleUnitTo.INCHES,
  fromValue: 1,
  toValue: 2,
}));

setMeasurementSnapping(enabled)

Allows the user to toggle the snapping behavior while creation of measurement annotations. The snapping points are the points are a combination of endpoints, midpoints and intersections.

Parameters:
Name Type Description
enabled boolean

Whether to enable/disable snapping behaviour for creation of measurement annotations.

setMentionableUsers(mentionableUsers)

Server only

Set a list of users that can be mentioned in comments.

Parameters:
Name Type Description
mentionableUsers Array.<MentionableUser>

An array of PSPDFKit.MentionableUser objects.

Example
instance.setMentionableUsers([
  { id: "1", name: "John Doe", displayName: "John", avatar: "https://example.com/avatar.png" },
  { id: "2", name: "Jane Doe", displayName: "Jane", avatar: "https://example.com/avatar.png" },
  { id: "3", name: "John Smith", displayName: "John", avatar: "https://example.com/avatar.png" },
]);

setOnAnnotationResizeStart(setOnAnnotationResizeStartCallback)

This method is used to update the setOnAnnotationResizeStart callback

When the supplied callback is invalid it will throw a PSPDFKit.Error that contains a detailed error message.

Parameters:
Name Type Description
setOnAnnotationResizeStartCallback PSPDFKit.AnnotationResizeStartCallback

setOnCommentCreationStart(callback) → {void}

You can programmatically modify the properties of the comment just before it is created.

Parameters:
Name Type Description
callback PSPDFKit.OnCommentCreationStartCallback

The callback to set the values of created form fields programmatically.

Returns:
Type
void
Example
instance.setOnCommentCreationStart((comment) => {
  return comment.set('text', { format: 'xhtml', value: '<p>This comment has a default value</p>' });
});

setOnWidgetAnnotationCreationStart(callback) → {void}

You can programmatically modify the properties of the widget annotation and the associated form field just before it is created via the form creator UI.

Parameters:
Name Type Description
callback PSPDFKit.OnWidgetAnnotationCreationStartCallback

The callback to set the values of created form fields programmatically.

Returns:
Type
void
Example
instance.setOnWidgetAnnotationCreationStart((annotation, formField) => {
  return { annotation: annotation.set('opacity', 0.7) };
});

setPageTabOrder(pageIndex, annotationIdsSortCallback)

*** Standalone only ***

This method is used to set the tab order of annotations in a given page.

The tab order should be provided as an array of annotation IDs.

In the case of widget annotations associated to a radio form field, all the widgets associated to the same form field will be rendered next to the first one found in the provided Array of annotation IDs.

Parameters:
Name Type Description
pageIndex number
annotationIdsSortCallback PSPDFKit.Instance~TabOrderUpdater

A callback that will get invoked with the annotations in the current tab order, and is expected to return the annotation IDs in the new tab order.

Throws:
Examples

Set the tab order of annotations in page 0

instance.setPageTabOrder(0, ["annotation-id-1", "annotation-id-2"]);

Set the tab order of annotations in page 0, with a radio form field

// 'radio-widget-id-2' will be rendered next to 'radio-widget-id-1', and navigated accordingly
instance.setPageTabOrder(0, ["radio-widget-id-1", "annotation-id-1", "annotation-id-2", "radio-widget-id-2"]);

setPageTabOrder(annotationIdsSortCallback)

This method is used to modify the current tab order of annotations.

Using this method, it is possible to specify the order in which annotations are navigated when using the keyboard.

The method accepts a page index as first argument, and a callback as second. This callback will be called with an array of annotations in the page sorted by their current tab order.

The callback should return an array of those annotations ids following the new tab order.

Parameters:
Name Type Description
annotationIdsSortCallback PSPDFKit.Instance~TabOrderUpdater

A callback that will get invoked with the annotations in the current tab order, and is expected to return the annotation IDs in the new tab order.

Throws:

Will throw an error when the supplied tab order is not valid.

Type
PSPDFKit.Error
Example

Sort page 1 annotations by their left position

instance.setPageTabOrder(
  1,
  currentTabOrderedAnnotations => currentTabOrderedAnnotations
    .sort((a, b) => a.boundingBox.left - b.boundingBox.left)
    .map(annotation => annotation.id)
);

setSearchState(SearchStateOrFunction)

This method is used to update the UI search state of the PDF editor.

When you pass in a PSPDFKit.SearchState, the current state will be immediately overwritten. Calling this method is also idempotent.

If you pass in a function, it will be immediately invoked and will receive the current PSPDFKit.SearchState as a property. You can use this to change state based on the current value. This type of update is guaranteed to be atomic - the value of currentState can't change in between. See: SearchStateUpdater

When the supplied PSPDFKit.SearchState is invalid, this method will throw an PSPDFKit.Error that contains a detailed error message.

PSPDFKit.SearchState#minSearchQueryLength is a readonly property and cannot be changed. If the provided PSPDFKit.SearchState object includes a modified minSearchQueryLength property, a warning will be shown and only changes to other properties will be applied.

Parameters:
Name Type Description
SearchStateOrFunction PSPDFKit.SearchState | PSPDFKit.Instance~SearchStateUpdater

Either a new SearchState which would overwrite the existing one, or a callback that will get invoked with the current search state and is expected to return the new state.

Throws:

Will throw an error when the supplied state is not valid.

Type
PSPDFKit.Error
Example

Update values for the immutable search state object

const state = instance.SearchState;
const newState = state.set("isLoading", true);
instance.setSearchState(newState);

setSelectedAnnotations(annotationsOrAnnotationsIdsnullable)

Selects annotations in the user interface. If annotationOrAnnotationId is empty, the current selection will be cleared instead.

Parameters:
Name Type Attributes Description
annotationsOrAnnotationsIds PSPDFKi.Immutable.List.<(AnnotationsUnion|string)> <nullable>

The annotations model or annotations IDs you want to set as selected. If null is used, the current selection will be cleared instead.

setSignaturesLTV(certificatesnullable) → {Promise.<PSPDFKit.SignaturesInfo>}

Standalone only

Adds LTV (Long Term Validation) information to an existing signature. See PSPDFKit.SignaturesInfo.

Parameters:
Name Type Attributes Description
certificates Array.<ArrayBuffer> | Array.<string> <nullable>

Certificates used to sign the document.

Returns:

Promise that resolves with a PSPDFKit.SignaturesInfo.

Type
Promise.<PSPDFKit.SignaturesInfo>
Example

Add LTV information to an existing signature

instance.setSignaturesLTV(certificates)
  .then(signaturesInfo => {
    console.log(signaturesInfo.status)
    if(signaturesInfo.signatures) {
      const invalidSignatures = signaturesInfo.signatures
        .filter(signature => !signature.ltv);
      console.log(invalidSignatures);
    }
});

Additional information can be found in
this guide article.

setStampAnnotationTemplates(stateOrFunction)

This method is used to update the stamp annotation templates.

It makes it possible to add new stamp and image annotation templates and edit or remove existing ones.

When you pass in an array with PSPDFKit.Annotations.StampAnnotation, the current templates will be immediately updated. Calling this method is also idempotent.

If you pass in a function, it will be immediately invoked and will receive the current Array<PSPDFKit.Annotations.StampAnnotation | PSPDFKit.Annotations.ImageAnnotation> Array as argument. You can use this to modify the array based on its current value. This type of update is guaranteed to be atomic - the value of currentStampAnnotationTemplates can't change in between. See: StampAnnotationTemplatesSetter

When one of the supplied PSPDFKit.Annotations.StampAnnotation or PSPDFKit.Annotations.ImageAnnotation is invalid, this method will throw a PSPDFKit.Error that contains a detailed error message.

Since stampAnnotationTemplates is a regular JavaScript Array, it can be manipulated using standard Array methods.

Parameters:
Name Type Description
stateOrFunction Array.<(PSPDFKit.Annotations.StampAnnotation|PSPDFKit.Annotations.ImageAnnotation)> | PSPDFKit.Instance~StampAnnotationTemplatesSetter

Either a new StampAnnotationTemplates Array which would overwrite the existing one, or a callback that will get invoked with the current stamp and image annotation templates and is expected to return the new stamp annotation stamps Array.

Throws:

Will throw an error when the supplied stamp annotation template array is not valid.

Type
PSPDFKit.Error
Examples

The new changes will be applied immediately

instance.setStampAnnotationTemplates(newStampAnnotationTemplates);
instance.stampAnnotationTemplates === newStampAnnotationTemplates; // => true

Adding a stamp annotation template.

const myStampAnnotationTemplate = new PSPDFKit.Annotations.StampAnnotation({
  stampType: "Custom",
  title: "My custom template title",
  subtitle: "Custom subtitle",
  boundingBox: new PSPDFKit.Geometry.Rect({ left: 0, top: 0, width: 192, height: 64 })
});
instance.setStampAnnotationTemplates(stampAnnotationTemplates => [ ...stampAnnotationTemplates, myStampAnnotationTemplate ]);

setStoredSignatures(StoredSignaturesOrFunction)

This method is used to update the stored signatures list. It makes it possible to add new signatures and edit or remove existing ones.

Signatures are either ink or image annotations whose pageIndex and boundingBox is calculated at creation time. When selected via UI such annotations are used as template to create new PSPDFKit.Annotations.InkAnnotations and PSPDFKit.Annotations.ImageAnnotations. . When you pass in a List of PSPDFKit.Annotations.InkAnnotation and PSPDFKit.Annotations.ImageAnnotation, the current list of signatures will be immediately updated. Calling this method is also idempotent.

If you pass in a function, it will be invoked with the current List of PSPDFKit.Annotations.InkAnnotation and PSPDFKit.Annotations.ImageAnnotation as argument. You can use this to modify the list based on its current value. This type of update is guaranteed to be atomic - the value of getStoredSignatures() can't change in between. See: StoredSignaturesSetter

When the application doesn't have signatures in store this method will invoke PSPDFKit.Configuration#populateStoredSignatures to retrieve the initial list of annotations and it will pass it to your function.

When the list is invalid, this method will throw an PSPDFKit.Error that contains a detailed error message.

Parameters:
Name Type Description
StoredSignaturesOrFunction Array.<PSPDFKit.ToolbarItem> | PSPDFKit.Instance~StoredSignaturesSetter

Either a new array of signatures which would overwrite the existing one, or a callback that will get invoked with the current toolbar items and is expected to return the new array of items.

Throws:

Will throw an error when the supplied items array is not valid.

Type
PSPDFKit.Error
Examples

Fetch and set a list of signatures

const signatures = fetch("/signatures")
  .then(r => r.json())
  .then(a => (
      new PSPDFKit.Immutable.List(
         a.map(PSPDFKit.Annotations.fromSerializableObject)
      )
    )
  );
signatures.then(signatures => { instance.setStoredSignatures(signatures) });

Use ES2015 arrow functions and the update callback to reduce boilerplate

instance.setStoredSignatures(signatures => signatures.reverse());

Add a Signature to the existing list

const signature = new PSPDFKit.Annotations.InkAnnotation({ lines: ..., boundingBox: ... });

instance.setStoredSignatures(signatures => signatures.push(signature));

Remove the first Signature from the list

instance.setStoredSignatures(signatures => signatures.shift());

setToolbarItems(toolbarItemsOrFunction)

This method is used to update the main toolbar items of the PDF editor. It makes it possible to add new items and edit or remove existing ones.

When you pass in an array of PSPDFKit.ToolbarItem, the current items will be immediately updated. Calling this method is also idempotent.

If you pass in a function, it will be immediately invoked and will receive the current array of PSPDFKit.ToolbarItem as argument. You can use this to modify the list based on its current value. This type of update is guaranteed to be atomic - the value of currentToolbarItems can't change in between. See: ToolbarItemsSetter

When one of the supplied PSPDFKit.ToolbarItem is invalid, this method will throw an PSPDFKit.Error that contains a detailed error message.

Since items is a regular JavaScript Array of object literals it can be manipulated using standard array methods like forEach, map, reduce, splice and so on. Additionally you can use any 3rd party library for array manipulation like lodash or just.

Parameters:
Name Type Description
toolbarItemsOrFunction Array.<PSPDFKit.ToolbarItem> | PSPDFKit.Instance~ToolbarItemsSetter

Either a new array of ToolbarItems which would overwrite the existing one, or a callback that will get invoked with the current toolbar items and is expected to return the new array of items.

Throws:

Will throw an error when the supplied items array is not valid.

Type
PSPDFKit.Error
Examples

Reverse the order of the toolbar items

const items = instance.toolbarItems;
items.reverse();
instance.setToolbarItems(newState);

Use ES2015 arrow functions and the update callback to reduce boilerplate

instance.setToolbarItems(items => items.reverse());

The new changes will be applied immediately

instance.setToolbarItems(newItems);
instance.toolbarItems === newItems; // => true

Adding a button that's always visible on the right hand side of the `zoom-in` button.

const myButton = {
  type: "custom",
  id: "my-button",
  title: "Test Button",
  icon: "https://example.com/icon.jpg",
  onPress() {
    alert("test");
  }
  // mediaQueries is not defined so it will always be shown
};
instance.setToolbarItems(items => {
  items.forEach((item, index) => {
    if (item.name === "spacer") {
      items.splice(index + 1, 0,  myButton);
    }
  });
  return items;
});

Changing a property of a custom button

const myButton = {
  type: "custom",
  id: "my-button",
  title: "Test Button",
  icon: "https://example.com/icon.jpg",
  disabled: true,
  onPress() {
    alert("test");
  },
};

PSPDFKit.load({
  toolbarItems: [...PSPDFKit.defaultToolbarItems, myButton],
  // ...
}).then(instance => {
  instance.setToolbarItems(items =>
    items.map(item => {
      if (item.id === "my-button") {
        item.disabled = false;
      }
      return item;
    })
  );
});

setViewState(stateOrFunction)

This method is used to update the UI state of the PDF editor.

When you pass in a PSPDFKit.ViewState, the current state will be immediately overwritten. Calling this method is also idempotent.

If you pass in a function, it will be immediately invoked and will receive the current PSPDFKit.ViewState as a property. You can use this to change state based on the current value. This type of update is guaranteed to be atomic - the value of currentState can't change in between. See: ViewStateUpdater

Be aware that this behavior is different from a React component's setState, because it will not be deferred but initially applied. If you want to, you can always add deferring behavior yourself. The approach we choose (immediate applying) makes it possible to control exactly when the changes are flushed, which will allow fine control to work with other frameworks (e.g. runloop-based frameworks like Ember).

Whenever this method is called (and actually changes the view state), the instance will trigger an PSPDFKit.Instance~ViewStateChangeEvent. However, if you use this method to change properties of the view state at once (e.g. zooming and currentPageIndex at the same time), the PSPDFKit.Instance~ViewStateChangeEvent will only be triggered once. The PSPDFKit.Instance~ViewStateChangeEvent will be triggered synchronously, that means that the code will be called before this function exits. This is true for both passing in the state directly and passing in an update function.

When the supplied PSPDFKit.ViewState is invalid, this method will throw an PSPDFKit.Error that contains a detailed error message.

Parameters:
Name Type Description
stateOrFunction PSPDFKit.ViewState | PSPDFKit.Instance~ViewStateUpdater

Either a new ViewState which would overwrite the existing one, or a callback that will get invoked with the current view state and is expected to return the new state.

Throws:

Will throw an error when the supplied state is not valid.

Type
PSPDFKit.Error
Examples

Update values for the immutable state object

const state = instance.viewState;
const newState = state.set("currentPageIndex", 2);
instance.setViewState(newState);

Use ES2015 arrow functions and the update callback to reduce boilerplate

instance.setViewState(state => state.set("currentPageIndex", 2));

The state will be applied immediately

instance.setViewState(newState);
instance.viewState === newState; // => true

When the state is invalid, it will throw a PSPDFKit.Error

try {
  // Non existing page index
  instance.setViewState(state => state.set("currentPageIndex", 2000));
} catch (error) {
  error.message; // => "The currentPageIndex set on the new ViewState is out of bounds.
                 //     The index is expected to be in the range from 0 to 5 (inclusive)"
}

signDocument(signaturePreparationDatanullable, twoStepSignatureCallbackOrSigningServiceDatanullable) → {Promise.<void>}

Digitally signs the document. On Standalone it can make sign the document with the certificates and private key provided by the user in PSPDFKit.SignaturePreparationData, or use the signing service optionally provided in the callback argument.

On Server, you can optionally specify additional data to be passed to the signing service.

Check the related guide article.

Parameters:
Name Type Attributes Description
signaturePreparationData PSPDFKit.SignaturePreparationData <nullable>

Properties to prepare the signature with.

twoStepSignatureCallbackOrSigningServiceData PSPDFKit.TwoStepSignatureCallback | PSPDFKit.SigningServiceData <nullable>

Either a callback to be executed when the document is ready for signing (Standalone only) or optional data to be passed to the signing service.

Returns:

Promise that resolves when the document is signed.

Type
Promise.<void>
Examples

Sign document with CMS signature (Standalone)

instance.signDocument(null, function({ hash, fileContents }) {
  return new Promise(function(resolve, reject) {
    const PKCS7Container = getPKCS7Container(hash, fileContents);
    if (PKCS7Container != null) {
      return resolve(PKCS7Container)
    }
    reject(new Error("Could not retrieve the PKCS7 container."))
  })
}).then(function() {
  console.log("Document signed!");
})

Sign document (Server)

instance.signDocument(null, { signingToken: "My security token" })
  .then(function() {
    console.log("Document signed!");
  })

startUISearch(term)

Open the search box, fill in the search term, and start loading the search requests.

This will set the PSPDFKit.ViewState#interactionMode to PSPDFKit.InteractionMode.SEARCH so that the search box is visible.

Parameters:
Name Type Description
term string

The search term.

Example

Start a search for the term `foo` in the UI

instance.startUISearch("foo");

textLinesForPageIndex(pageIndex) → {Promise.<PSPDFKit.Immutable.List.<PSPDFKit.TextLine>>}

Load all PSPDFKit.TextLines for the specified pageIndex. If there is no page at the given index, the list will be empty.

Parameters:
Name Type Description
pageIndex number

The index of the page you want to extract text from.

Returns:

A promise that resolves the text lines of the given page.

Type
Promise.<PSPDFKit.Immutable.List.<PSPDFKit.TextLine>>

toggleClipboardActions(enabled)

Enable actions like cut, copy, paste and duplicate for annotations using keyboard shortcuts Cmd/Ctrl+X, Cmd/Ctrl+C, Cmd/Ctrl+V and Cmd/Ctrl+D respectively.

Parameters:
Name Type Description
enabled boolean

Whether to enable/disable the clipboard actions.

transformClientToPageSpace(rectOrPoint, pageIndex) → {PSPDFKit.Geometry.Rect|PSPDFKit.Geometry.Point}

Transforms a PSPDFKit.Geometry.Point or a PSPDFKit.Geometry.Rect from the client space inside the main frame to the PDF page space.

The client space is relative to your HTML viewport and the same coordinates that you receive by DOM APIs like Element.getBoundingClientRect() or MouseEvent.clientX, etc.

Use this transform when you receive events inside the main frame (The document of your application).

Note: If you apply a CSS scale transformation to the mounting node of PSPDFKit for Web, this calculation will not work. In this case make sure to manually scale afterwards.

Parameters:
Name Type Description
rectOrPoint PSPDFKit.Geometry.Rect | PSPDFKit.Geometry.Point

The rectangle or point that needs to be transformed

pageIndex number

The index of the page you want to have information about. If none is provided, the first page (pageIndex 0) will be used.

Throws:

Will throw an error when the supplied arguments is not valid.

Type
PSPDFKit.Error
Returns:

The transformed point or rectangle.

Type
PSPDFKit.Geometry.Rect | PSPDFKit.Geometry.Point

transformContentClientToPageSpace(rectOrPoint, pageIndex) → {PSPDFKit.Geometry.Rect|PSPDFKit.Geometry.Point}

Transforms a PSPDFKit.Geometry.Point or a PSPDFKit.Geometry.Rect from the client space inside the content frame to the PDF page space.

The content client space is relative to the PSPDFKit mounting container and the same coordinates that you receive by DOM APIs like Element.getBoundingClientRect() or MouseEvent.clientX, etc. that originate within the PSPDFKit for Web iframe.

Use this transform when you receive events inside the content frame.

Parameters:
Name Type Description
rectOrPoint PSPDFKit.Geometry.Rect | PSPDFKit.Geometry.Point

The rectangle or point that needs to be transformed

pageIndex number

The index of the page you want to have information about. If none is provided, the first page (pageIndex 0) will be used.

Throws:

Will throw an error when the supplied arguments is not valid.

Type
PSPDFKit.Error
Returns:

The transformed point or rectangle.

Type
PSPDFKit.Geometry.Rect | PSPDFKit.Geometry.Point

transformContentPageToClientSpace(rectOrPoint, pageIndex) → {PSPDFKit.Geometry.Rect|PSPDFKit.Geometry.Point}

Transforms a PSPDFKit.Geometry.Point or a PSPDFKit.Geometry.Rect from the PDF page space to the client space inside the content frame.

The content client space is relative to the PSPDFKit mounting container and the same coordinates that you receive by DOM APIs like Element.getBoundingClientRect() or MouseEvent.clientX, etc. that originate within the PSPDFKit for Web iframe.

Use this transform when you want to position elements inside the PSPDFKit content frame.

Parameters:
Name Type Description
rectOrPoint PSPDFKit.Geometry.Rect | PSPDFKit.Geometry.Point

The rectangle or point that needs to be transformed

pageIndex number

The index of the page you want to have information about. If none is provided, the first page (pageIndex 0) will be used.

Throws:

Will throw an error when the supplied arguments is not valid.

Type
PSPDFKit.Error
Returns:

The transformed point or rectangle.

Type
PSPDFKit.Geometry.Rect | PSPDFKit.Geometry.Point

transformPageToClientSpace(rectOrPoint, pageIndex) → {PSPDFKit.Geometry.Rect|PSPDFKit.Geometry.Point}

Transforms a PSPDFKit.Geometry.Point or a PSPDFKit.Geometry.Rect from the PDF page space to the client space inside the main frame.

The client space is relative to your HTML viewport and the same coordinates that you receive by DOM APIs like Element.getBoundingClientRect() or MouseEvent.clientX, etc.

Use this transform when you want to position elements inside the main frame.

Note: If you apply a CSS scale transformation to the mounting node of PSPDFKit for Web, this calculation will not work. In this case make sure to manually scale afterwards.

Parameters:
Name Type Description
rectOrPoint PSPDFKit.Geometry.Rect | PSPDFKit.Geometry.Point

The rectangle or point that needs to be transformed

pageIndex number

The index of the page you want to have information about. If none is provided, the first page (pageIndex 0) will be used.

Throws:

Will throw an error when the supplied arguments is not valid.

Type
PSPDFKit.Error
Returns:

The transformed point or rectangle.

Type
PSPDFKit.Geometry.Rect | PSPDFKit.Geometry.Point

transformPageToRawSpace(rect, pageIndex) → {PSPDFKit.Geometry.Inset}

Transforms a PSPDFKit page space bounding box to a raw PDF bounding rect.

A raw PDF bounding rect is an array of inset values: [left, bottom, right, top], in PDF page space units (as opposted to PSPDFKit page units) where the top and bottom coordinates are actually relative to the distance to the bottom of the page.

Use this transform when you want to manage document entities with external tools.

Parameters:
Name Type Description
rect PSPDFKit.Geometry.Rect

The rectangle to be transformed

pageIndex number

The index of the page you want to have information about.

Throws:

Will throw an error when the supplied arguments is not valid.

Type
PSPDFKit.Error
Returns:

The resulting transformed rectangle as inset coordinates.

Type
PSPDFKit.Geometry.Inset

transformRawToPageSpace(insetOrRawInset, pageIndex) → {PSPDFKit.Geometry.Rect}

Transforms a raw PDF bounding rect from the PDF page space to PSPDFKit's page space.

Use this transform when you want to manage entities using their raw, original coordinates and dimensions according to the PDF spec (e.g. from a XFDF file).

Parameters:
Name Type Description
insetOrRawInset PSPDFKit.Geometry.Inset | Array.<number>

The inset to be transformed

pageIndex number

The index of the page you want to have information about.

Throws:

Will throw an error when the supplied arguments is not valid.

Type
PSPDFKit.Error
Returns:

The resulting transformed rectangle.

Type
PSPDFKit.Geometry.Rect

update(changes) → {Promise.<Array.<PSPDFKit.Change>>}

Updates object and changes its contents.

If you need to ensure that changes are persisted by the backend, please refer to: PSPDFKit.Instance#ensureChangesSaved.

New changes will be made visible in the UI instantly.

Parameters:
Name Type Description
changes PSPDFKit.Change | Array.<PSPDFKit.Change> | List.<PSPDFKit.Change>

A single change or list/array of changes that should be updated.

Returns:

A promise that resolves to an array of changes or an error if some changes could not be updated.

Type
Promise.<Array.<PSPDFKit.Change>>
Example
const instance = await PSPDFKit.load(configuration);
// Get all annotations on the first page
const annotations = instance.getAnnotations(0);
// Grab the first one
const annotation = annotations.first();

const editedAnnotation = annotation.set("noPrint", true);
const updatedAnnotation = await instance.update(editedAnnotation);

editedAnnotation === updatedAnnotation; // => true

(inner) setInlineTextSelectionToolbarItems(inlineTextSelectionToolbarItemsCallback)

You can use this callback to set/modify the toolbar items present in the inline toolbar after the document has loaded.

The callback will receive the default items of the inline toolbar and the text that is currently selected {@linkPSPDFKit.TextSelection}

You can do the following modifications using this API:

  • Add new items.
  • Remove existing items.
  • Change the order of the items.
  • Customise each item eg change the icon of the a default toolbar item.

You can also use the hasDesktopLayout flag provided to the callback to determine if the current UI is being rendered on mobile or desktop. Based on that, you can implement different designs for Desktop and Mobile.

This callback gets called every time the inline toolbar is mounted.

Parameters:
Name Type Description
inlineTextSelectionToolbarItemsCallback PSPDFKit.InlineTextSelectionToolbarItemsCallback
Example

Add a custom button and a custom node to the toolbar.

instance.setInlineTextSelectionToolbarItems(({ defaultItems, hasDesktopLayout }, selection) => {
 console.log(selection)
 if (hasDesktopLayout) {
   const node = document.createElement("div");
   node.innerText = "Custom Item";
     return [
       ...defaultItems,
       {
         type: "custom",
         id: "custom-1",
         node: node,
         className: "Custom-Node",
         onPress: () => alert("Custom node pressed!"),
       },
       {
         type: "custom",
         id: "custom-2",
         title: "custom-button-2",
         onPress: () => alert("Custom item pressed!"),
       },
     ];
    }
   return defaultItems
  });

Type Definitions

AnnotationNoteHoverEvent(event)

This event will be emitted whenever an annotation note icon is hovered, which by default shows the annotation note editor popover element.

The parameter is a PSPDFKit.AnnotationNotePressEvent.

Parameters:
Name Type Description
event PSPDFKit.AnnotationNoteHoverEvent
Example

Register a AnnotationNoteHoverEvent handler and prevent the default annotation note UI from showing.

instance.addEventListener("annotationNote.hover", (event) => {
  event.preventDefault();
});

AnnotationNotePressEvent(event)

This event will be emitted whenever an annotation note is selected by pressing its associated icon.

The parameter is a PSPDFKit.AnnotationNotePressEvent.

Parameters:
Name Type Description
event PSPDFKit.AnnotationNotePressEvent
Example

Register a AnnotationNotePressEvent handler and prevent the default annotation note UI from showing.

instance.addEventListener("annotationNote.press", (event) => {
  event.preventDefault();
});

AnnotationPresetsSetter(currentAnnotationPresets) → {Object.<string, PSPDFKit.AnnotationPreset>}

This callback can be used in the setAnnotationPresets() method to do atomic updates to the current annotation presets.

Parameters:
Name Type Description
currentAnnotationPresets Object.<string, PSPDFKit.AnnotationPreset>
Returns:

The new annotation presets.

Type
Object.<string, PSPDFKit.AnnotationPreset>
Example

Use ES2015 arrow functions and the update callback to reduce boilerplate

instance.setAnnotationPresets(presets => {
  presets.custom = {
    strokeWidth: 10,
  };
  return presets;
});

AnnotationPresetsUpdateEvent(event)

This event will be emitted whenever the current preset is about to be updated with new property values set by the user in the annotation toolbar.

The parameter is a PSPDFKit.AnnotationPresetsUpdateEvent.

Parameters:
Name Type Description
event PSPDFKit.AnnotationPresetsUpdateEvent
Example

Register a PresetOnUpdate and prevent the current preset from being updated.

instance.addEventListener("annotationPresets.update", (event) => {
  event.preventDefault();
});

AnnotationSelectionChangeEvent(annotations)

This event will fire whenever an annotation is being selected or unselected.

Parameters:
Name Type Description
annotations PSPDFKit.Immutable.List.<AnnotationsUnion>

The newly selected annotations, if any.

Example

Register a AnnotationSelectionChangeEvent

instance.addEventListener("annotationSelection.change", (annotations) => {
  if (annotations.size !== 0) {
    console.log("annotation is selected");
  } else {
    console.log("no annotation is selected");
  }
});

AnnotationsBlurEvent(event)

This event will be emitted whenever an annotation loses focus.

The parameter is a PSPDFKit.AnnotationsBlurEvent.

Parameters:
Name Type Description
event PSPDFKit.AnnotationsBlurEvent
Example

Register a AnnotationsBlurEvent.

instance.addEventListener("annotations.blur", (event) => {
  console.log(event.annotation, event.nativeEvent.type)
});

AnnotationsChangeEvent()

This event will be emitted whenever the current annotations change either due to a user action (eg. clicking the UI) or via PSPDFKit.Instance#create, PSPDFKit.Instance#update or PSPDFKit.Instance#delete.

The event might also be emitted every time the PSPDFKit's annotations model changes. This for example can happen when scrolling to a page and PSPDFKit loads the annotations for that page or when opening the annotations sidebar and PSPDFKit (has to) loads all the document annotations.

The change event will fire before all specific events and it could be used in case you want to perform some action regardless of which event caused the annotation to "change" (create, delete, update, load, internal load, etc). Consider using the specific events for more advanced use cases.

Example

Register a AnnotationsChangeEvent

instance.addEventListener("annotations.change", () => {
  // ...
});

AnnotationsCopyEvent(event)

This event will be emitted whenever an annotation is copied using Cmd/Ctrl+C keyboard shortcut.

The parameter is a PSPDFKit.AnnotationsCopyEvent

Parameters:
Name Type Description
event PSPDFKit.AnnotationsCopyEvent
Example

Register a AnnotationsCopyEvent.

instance.addEventListener("annotations.copy", (event) => {
  console.log(event.annotation)
});

AnnotationsCreateEvent(createdAnnotations)

This event will be emitted whenever new annotations were created (either via the public API or via the UI).

If PSPDFKit Instant is enabled, annotations created by remote clients will also cause this event to be emitted.

The parameter is a PSPDFKit.Immutable.List of created PSPDFKit.Annotations.

Parameters:
Name Type Description
createdAnnotations PSPDFKit.Immutable.List.<AnnotationsUnion>
Example

Register a AnnotationsCreateEvent

instance.addEventListener("annotations.create", (createdAnnotations) => {
  console.log(createdAnnotations);
});

AnnotationsCutEvent(event)

This event will be emitted whenever an annotation is cut using Cmd/Ctrl+X keyboard shortcut.

The parameter is a PSPDFKit.AnnotationsCutEvent

Parameters:
Name Type Description
event PSPDFKit.AnnotationsCutEvent
Example

Register a AnnotationsCutEvent.

instance.addEventListener("annotations.cut", (event) => {
  console.log(event.annotation)
});

AnnotationsDeleteEvent(deletedAnnotations)

This event will be emitted whenever new annotations were deleted (either via the public API or via the UI).

The parameter is a PSPDFKit.Immutable.List of deleted PSPDFKit.Annotations.

Parameters:
Name Type Description
deletedAnnotations PSPDFKit.Immutable.List.<AnnotationsUnion>
Example

Register a AnnotationsDeleteEvent

instance.addEventListener("annotations.delete", (deletedAnnotations) => {
  console.log(deletedAnnotations);
});

AnnotationsDidSaveEvent()

This event will be emitted whenever annotations were saved to the annotation provider.

This event will follow a PSPDFKit.Instance~AnnotationsWillSaveEvent.

Example

Register a AnnotationsDidSaveEvent

instance.addEventListener("annotations.didSave", () => {
  // ...
});

AnnotationsDuplicateEvent(event)

This event will be emitted whenever an annotation is duplicated using the Ctrl/Cmd+D keyboard shortcut.

The parameter is a PSPDFKit.AnnotationsDuplicateEvent

Parameters:
Name Type Description
event PSPDFKit.AnnotationsDuplicateEvent
Example

Register a AnnotationsDuplicateEvent.

instance.addEventListener("annotations.duplicate", (event) => {
  console.log(event.annotation)
});

AnnotationsFocusEvent(event)

This event will be emitted whenever an annotation is focused.

The parameter is a PSPDFKit.AnnotationsFocusEvent.

Parameters:
Name Type Description
event PSPDFKit.AnnotationsFocusEvent
Example

Register a AnnotationsFocusEvent.

instance.addEventListener("annotations.focus", (event) => {
  console.log(event.annotation, event.nativeEvent.type)
});

AnnotationsLoadEvent(loadedAnnotations)

This event will be emitted whenever annotations are loaded from the annotation provider. This can happen more than once since we often load annotations on demand only.

The parameter is a PSPDFKit.Immutable.List of loaded PSPDFKit.Annotations.

Parameters:
Name Type Description
loadedAnnotations PSPDFKit.Immutable.List.<AnnotationsUnion>
Example

Register a AnnotationsLoadEvent

instance.addEventListener("annotations.load", (loadedAnnotations) => {
  console.log(loadedAnnotations);
});

AnnotationsPasteEvent(event)

This event will be emitted whenever an annotation is pasted using Cmd/Ctrl+V keyboard shortcut.

The parameter is a PSPDFKit.AnnotationsPasteEvent

Parameters:
Name Type Description
event PSPDFKit.AnnotationsPasteEvent
Example

Register a AnnotationsPasteEvent.

instance.addEventListener("annotations.paste", (event) => {
  console.log(event.annotations)
});

AnnotationsPressEvent(event)

This event will be emitted whenever an annotation is pressed i.e. either clicked or tapped.

The parameter is a PSPDFKit.AnnotationsPressEvent.

Parameters:
Name Type Description
event PSPDFKit.AnnotationsPressEvent
Example

Register a AnnotationsPressEvent, prevent the default behavior for LinkAnnotation and redirect to another site.

instance.addEventListener("annotations.press", (event) => {
  if (event.annotation instanceof PSPDFKit.Annotations.LinkAnnotation) {
    event.preventDefault();
    window.location.href = "https://example.com";
.  }
});

AnnotationsTransformEvent(event)

This event will be emitted whenever an annotation is dragged or resized using the UI.

The parameter is a PSPDFKit.AnnotationsTransformEvent

Parameters:
Name Type Description
event PSPDFKit.AnnotationsTransformEvent
Example

Register a AnnotationsTransformEvent.

instance.addEventListener("annotations.transform", (event) => {
  console.log(event.annotation.boundingBox)
});

AnnotationsUpdateEvent(updatedAnnotations)

This event will be emitted whenever new annotations were updated (either via the public API or via the UI).

The parameter is a PSPDFKit.Immutable.List of updated PSPDFKit.Annotations.

Parameters:
Name Type Description
updatedAnnotations PSPDFKit.Immutable.List.<AnnotationsUnion>
Example

Register a AnnotationsUpdateEvent

instance.addEventListener("annotations.update", (updatedAnnotations) => {
  console.log(updatedAnnotations);
});

AnnotationsWillChangeEvent(event)

This event will be emitted when the user starts or ends an interaction with an annotation. See PSPDFKit.AnnotationsWillChangeReason for a comprehensive list of actions supported.

Note that this event is only emitted for actions performed through the UI.

Despite the name, it is not necessarily fired before each emission of PSPDFKit.Instance~AnnotationsChangeEvent, since that would not correspond to the list of possible reasons described in PSPDFKit.AnnotationsWillChangeReason on all cases.

Parameters:
Name Type Description
event PSPDFKit.AnnotationsWillChangeEvent
Example

Register a AnnotationsWillChangeEvent

instance.addEventListener("annotations.willChange", event => {
  const annotation = event.annotations.get(0);
  if (event.reason === PSPDFKit.AnnotationsWillChangeReason.DELETE_START) {
    console.log("Will open deletion confirmation dialog");
  } else if (
    event.reason === PSPDFKit.AnnotationsWillChangeReason.DELETE_END
  ) {
    if (annotation) {
      console.log("The user decided to delete the annotation.");
    } else {
      console.log("The user decided to not delete the annotation.");
    }
  }
});

AnnotationsWillSaveEvent()

This event will be emitted before annotations will be saved to the annotation provider.

Right now, this happens whenever attributes of the annotation change (either via the public API or via the UI) and the annotation is in a valid state.

You can use this to display a loading spinner for example. This event will always be followed by PSPDFKit.Instance~AnnotationsDidSaveEvent.

Example

Register a AnnotationsWillSaveEvent

instance.addEventListener("annotations.willSave", () => {
  // ...
});

BookmarksChangeEvent()

This event will be emitted whenever the current bookmarks change either via PSPDFKit.Instance#createBookmark, PSPDFKit.Instance#updateBookmark or PSPDFKit.Instance#deleteBookmark.

The change event will fire before all specific events. Consider using the specific events for more advanced use cases.

Example

Register a BookmarksChangeEvent

instance.addEventListener("bookmarks.change", () => {
  // ...
});

BookmarksCreateEvent(createdBookmarks)

This event will be emitted whenever new bookmarks are created (either via the public API or via the UI).

The parameter is a PSPDFKit.Immutable.List of created PSPDFKit.Bookmark.

Parameters:
Name Type Description
createdBookmarks PSPDFKit.Immutable.List.<PSPDFKit.Bookmark>
Example

Register a BookmarksCreateEvent

instance.addEventListener("bookmarks.create", (createdBookmarks) => {
  console.log(createdBookmarks);
});

BookmarksDeleteEvent(deletedBookmarks)

This event will be emitted whenever bookmarks are deleted (either via the public API or via the UI).

The parameter is a PSPDFKit.Immutable.List of deleted PSPDFKit.Bookmark.

Parameters:
Name Type Description
deletedBookmarks PSPDFKit.Immutable.List.<PSPDFKit.Bookmark>
Example

Register a BookmarksDeleteEvent

instance.addEventListener("bookmarks.delete", (deletedBookmarks) => {
  console.log(deletedBookmarks);
});

BookmarksDidSaveEvent()

This event will be emitted whenever bookmarks were saved to the bookmark provider.

This event will follow a PSPDFKit.Instance~BookmarksWillSaveEvent.

Example

Register a BookmarksDidSaveEvent

instance.addEventListener("bookmarks.didSave", () => {
  // ...
});

BookmarksLoadEvent(loadedBookmarks)

This event will be emitted whenever bookmarks are loaded from the bookmark provider. This can happen more than once since we often load bookmarks on demand only.

The parameter is a PSPDFKit.Immutable.List of loaded PSPDFKit.Bookmark.

Parameters:
Name Type Description
loadedBookmarks PSPDFKit.Immutable.List.<PSPDFKit.Bookmark>
Example

Register a BookmarksLoadEvent

instance.addEventListener("bookmarks.load", (loadedBookmarks) => {
  console.log(loadedBookmarks);
});

BookmarksUpdateEvent(updatedBookmarks)

This event will be emitted whenever bookmarks are updated (either via the public API or via the UI).

The parameter is a PSPDFKit.Immutable.List of updated PSPDFKit.Bookmark.

Parameters:
Name Type Description
updatedBookmarks PSPDFKit.Immutable.List.<PSPDFKit.Bookmark>
Example

Register a BookmarksUpdateEvent

instance.addEventListener("bookmarks.update", (updatedBookmarks) => {
  console.log(updatedBookmarks);
});

BookmarksWillSaveEvent()

This event will be emitted before bookmarks will be saved to the bookmark provider.

Right now, this happens whenever attributes of the bookmark change (either via the public API or via the UI) and the bookmark is in a valid state.

You can use this to display a loading spinner for example. This event will always be followed by PSPDFKit.Instance~BookmarksDidSaveEvent.

Example

Register a BookmarksWillSaveEvent

instance.addEventListener("bookmarks.willSave", () => {
  // ...
});

CommentsChangeEvent()

This event will be emitted whenever the current comments change either via PSPDFKit.Instance#create, PSPDFKit.Instance#update or PSPDFKit.Instance#delete.

The change event will fire before all specific events. Consider using the specific events for more advanced use cases.

Example

Register a CommentsChangeEvent

instance.addEventListener("comments.change", () => {
  // ...
});

CommentsCreateEvent(createdComments)

This event will be emitted whenever new comments are created (either via the public API or via the UI).

The parameter is a PSPDFKit.Immutable.List of created PSPDFKit.Comment.

Parameters:
Name Type Description
createdComments PSPDFKit.Immutable.List.<PSPDFKit.Comment>
Example

Register a CommentsCreateEvent

instance.addEventListener("comments.create", (createdComments) => {
  console.log(createdComments);
});

CommentsDeleteEvent(deletedComments)

This event will be emitted whenever comments are deleted (either via the public API or via the UI).

The parameter is a PSPDFKit.Immutable.List of deleted PSPDFKit.Comment.

Parameters:
Name Type Description
deletedComments PSPDFKit.Immutable.List.<PSPDFKit.Comment>
Example

Register a CommentsDeleteEvent

instance.addEventListener("comments.delete", (deletedComments) => {
  console.log(deletedComments);
});

CommentsDidSaveEvent()

This event will be emitted whenever comments were saved to the comment provider.

This event will follow a PSPDFKit.Instance~CommentsWillSaveEvent.

Example

Register a CommentsDidSaveEvent

instance.addEventListener("comments.didSave", () => {
  // ...
});

CommentsLoadEvent(loadedComments)

This event will be emitted whenever comments are loaded from the comment provider. This can happen more than once since we often load comments on demand only.

The parameter is a PSPDFKit.Immutable.List of loaded PSPDFKit.Comment.

Parameters:
Name Type Description
loadedComments PSPDFKit.Immutable.List.<PSPDFKit.Comment>
Example

Register a CommentsLoadEvent

instance.addEventListener("comments.load", (loadedComments) => {
  console.log(loadedComments);
});

CommentsUpdateEvent(updatedComments)

This event will be emitted whenever comments are updated (either via the public API or via the UI).

The parameter is a PSPDFKit.Immutable.List of updated PSPDFKit.Comment.

Parameters:
Name Type Description
updatedComments PSPDFKit.Immutable.List.<PSPDFKit.Comment>
Example

Register a CommentsUpdateEvent

instance.addEventListener("comments.update", (updatedComments) => {
  console.log(updatedComments);
});

CommentsWillSaveEvent()

This event will be emitted before comments will be saved to the comment provider.

Right now, this happens whenever attributes of the comment change (either via the public API or via the UI) and the comment is in a valid state.

You can use this to display a loading spinner for example. This event will always be followed by PSPDFKit.Instance~CommentsDidSaveEvent.

Example

Register a CommentsWillSaveEvent

instance.addEventListener("comments.willSave", () => {
  // ...
});

ConnectedClientsChangeEvent(connectedClients)
Server Only

This event will be emitted whenever an instant client connects or disconnects from the current document. See PSPDFKit.Instance#connectedClients for more information.

To receive this callback, make sure to set up PSPDFKit Instant correctly.

Parameters:
Name Type Description
connectedClients Immutable.Map.<string, PSPDFKit.InstantClient>

An up-to-date list of currently connected instant clients.

Example

Register a ConnectedClientsChangeEvent

instance.addEventListener("instant.connectedClients.change", (clients) => {
  console.log(clients.toJS());
});

CropAreaChangeStartEvent(event)

This event will be emitted whenever the CropArea begins being created, moved, or resized (via UI interaction).

Parameters:
Name Type Description
event PSPDFKit.CropAreaChangeStartEvent
Example

Register a CropAreaChangeStartEvent

instance.addEventListener("cropArea.changeStart", ({ area, pageIndex }) => {
  console.log(area, pageIndex);
});

CropAreaChangeStopEvent(event)

This event will be emitted whenever the crop area stops being created, moved or resized (via UI interaction).

Parameters:
Name Type Description
event PSPDFKit.CropAreaChangeStopEvent
Example

Register a CropAreaChangeStopEvent

instance.addEventListener("cropArea.changeStop", ({ area, pageIndex }) => {
  console.log(area, pageIndex);
});

DocumentChangeEvent()

This event will be emitted whenever operations have been performed in the document.

The event listener will receive the array of operations performed on the document.

Example

Register a DocumentChangeEvent

instance.addEventListener("document.change", (operations) => {
  // ...
});

DocumentComparisonUIEndEvent()

This event will be emitted whenever the document comparison UI is hidden.

Example

Register a DocumentComparisonUIEndEvent

instance.addEventListener("documentComparisonUI.end", () => {
  // ...
});

DocumentComparisonUIStartEvent()

This event will be emitted whenever the document comparison UI is shown.

The event listener will receive the document comparison configuration object with which setDocumentComparisonMode() has been called.

Example

Register a DocumentComparisonUIStartEvent

instance.addEventListener("documentComparisonUI.start", (documentComparisonConfiguration) => {
  // ...
});

DocumentEditorFooterItemsSetter(currentDocumentEditorFooterItems) → {Array.<PSPDFKit.DocumentEditorFooterItem>}

This callback can be used in the setDocumentEditorFooterItems() method to do atomic updates to the document editor footer items.

Parameters:
Name Type Description
currentDocumentEditorFooterItems Array.<PSPDFKit.DocumentEditorFooterItem>
Returns:

The new document editor footer items.

Type
Array.<PSPDFKit.DocumentEditorFooterItem>
Example

Use ES2015 arrow functions and the update callback to reduce boilerplate

instance.setDocumentEditorFooterItems(items => {
  const button = instance.contentDocument.createElement('div');
  button.innerText = "Custom Save"
  items.push({
    type: "custom",
    node: button,
    onPress(){
      alert("save");
    }
  });
  return items;
});

DocumentEditorToolbarItemsSetter(currentDocumentEditorToolbarItems) → {Array.<PSPDFKit.DocumentEditorToolbarItem>}

This callback can be used in the setDocumentEditorToolbarItems() method to do atomic updates to the document editor toolbar items.

Parameters:
Name Type Description
currentDocumentEditorToolbarItems Array.<PSPDFKit.DocumentEditorToolbarItem>
Returns:

The new document editor toolbar items.

Type
Array.<PSPDFKit.DocumentEditorToolbarItem>
Example

Use ES2015 arrow functions and the update callback to reduce boilerplate

instance.setDocumentEditorToolbarItems(items => {
  const button = instance.contentDocument.createElement('div');
  button.innerText = "Do something"
  items.push({
    type: "custom",
    node: button,
    onPress(){
      alert("Do Something");
    }
  });
  return items;
});

FormDidSubmitEvent()

This event will be emitted whenever the form got submitted to the specified URI. The event will receive a object from the form submission. If the submission got transmitted successfully, the object will contain a response key, which has a response object as a value. When an error occurred during the submission, the object parameter will have an error key with the error object as a value.

Example

Register a FormFieldValuesDidSaveEvent

instance.addEventListener("formFieldValues.didSave", ({ response, error }) => {
  // ...
});

FormFieldValuesDidSaveEvent()

This event will be emitted whenever the form field values were saved to the data provider.

This event will follow a PSPDFKit.Instance~FormFieldValuesWillSaveEvent.

Example

Register a FormFieldValuesDidSaveEvent

instance.addEventListener("formFieldValues.didSave", () => {
  // ...
});

FormFieldValuesUpdateEvent(updatedFormFields)

This event will be emitted whenever the current value of form field were updated either due to a user action or when PSPDFKit.Instance#setFormFieldValues is invoked.

Parameters:
Name Type Description
updatedFormFields PSPDFKit.Immutable.List.<PSPDFKit.FormFields.FormField>
Example

Register a FormFieldValuesUpdateEvent

instance.addEventListener("formFieldValues.update", formFields => {
  // ...
});

FormFieldValuesWillSaveEvent()

This event will be emitted before form field values will be saved to the data provider.

You can use this to display a loading spinner, for example. This event will always be followed by PSPDFKit.Instance~FormFieldValuesDidSaveEvent.

Example

Register a FormFieldValuesWillSaveEvent

instance.addEventListener("formFieldValues.willSave", () => {
  // ...
});

FormFieldsChangeEvent()

This event will be emitted whenever the current form fields change either due to a user action (eg. clicking the UI) or via PSPDFKit.Instance#create, PSPDFKit.Instance#update or PSPDFKit.Instance#delete.

The change event will fire before all specific events and it could be used in case you want to perform some action regardless of which event caused the form fields to "change" (create, delete, update, load, internal load, etc). Consider using the specific events for more advanced use cases.

Example

Register a FormFieldsChangeEvent

instance.addEventListener("formFields.change", () => {
  // ...
});

FormFieldsCreateEvent(createdFormFields)

This event will be emitted whenever new form fields where created (either via the public API or via the UI).

The parameter is a PSPDFKit.Immutable.List of created PSPDFKit.FormFields.

Parameters:
Name Type Description
createdFormFields PSPDFKit.Immutable.List.<PSPDFKit.FormFields.FormField>
Example

Register a FormFieldsCreateEvent

instance.addEventListener("formFields.create", (createdFormFields) => {
  console.log(createdFormFields);
});

FormFieldsDeleteEvent(deletedFormFields)

This event will be emitted whenever new form fields where deleted (either via the public API or via the UI).

The parameter is a PSPDFKit.Immutable.List of deleted PSPDFKit.FormFields.

Parameters:
Name Type Description
deletedFormFields PSPDFKit.Immutable.List.<PSPDFKit.FormFields.FormField>
Example

Register a FormFieldsDeleteEvent

instance.addEventListener("formFields.delete", (deletedFormFields) => {
  console.log(deletedFormFields);
});

FormFieldsDidSaveEvent()

This event will be emitted whenever form fields were saved to the form field provider.

This event will follow a PSPDFKit.Instance~FormFieldsWillSaveEvent.

Example

Register a FormFieldsDidSaveEvent

instance.addEventListener("formFields.didSave", () => {
  // ...
});

FormFieldsLoadEvent(loadedFormFields)

This event will be emitted whenever form fields are loaded from the form field provider. This can happen more than once since we often load form fields on demand only.

The parameter is a PSPDFKit.Immutable.List of loaded PSPDFKit.FormFields.

Parameters:
Name Type Description
loadedFormFields PSPDFKit.Immutable.List.<PSPDFKit.FormFields.FormField>
Example

Register a FormFieldsLoadEvent

instance.addEventListener("formFields.load", (loadedFormFields) => {
  console.log(loadedFormFields);
});

FormFieldsUpdateEvent(updatedFormFields)

This event will be emitted whenever new form fields where updated (either via the public API or via the UI).

The parameter is a PSPDFKit.Immutable.List of updated PSPDFKit.FormFields.

Parameters:
Name Type Description
updatedFormFields PSPDFKit.Immutable.List.<PSPDFKit.FormFields.FormField>
Example

Register a FormFieldsUpdateEvent

instance.addEventListener("formFields.update", (updatedFormFields) => {
  console.log(updatedFormFields);
});

FormFieldsWillSaveEvent()

This event will be emitted before form fields will be saved to the form field provider.

Right now, this happens whenever attributes of the form fields change (either via the public API or via the UI) and the form field is in a valid state.

You can use this to display a loading spinner for example. This event will always be followed by PSPDFKit.Instance~FormFieldsDidSaveEvent.

Example

Register a FormFieldsWillSaveEvent

instance.addEventListener("formFields.willSave", () => {
  // ...
});

FormWillSubmitEvent()

This event will be emitted whenever the form values will be submitted.

To cancel the form submission, call the preventDefault function with no arguments. This event will follow a PSPDFKit.Instance~FormDidSubmitEvent, when the submission got not canceled with preventDefault.

Example

Register a FormWillSubmitEvent

instance.addEventListener("forms.willSubmit", ({ preventDefault }) => {
  // ...
});

HistoryChangeEvent(event)

This event will be emitted after calling PSPDFKit.Instance.history.undo or PSPDFKit.Instance.history.redo, or after pressing the main toolbar Undo or Redo buttons, optionally available.

If provided, the listener callback will receive a PSPDFKit.HistoryChangeEvent object.

Parameters:
Name Type Description
event PSPDFKit.HistoryChangeEvent
Example

Register a HistoryChangeEvent

instance.addEventListener("history.change", (historyChangeEvent) => {
  console.log(historyChangeEvent);
});

HistoryClearEvent()

This event will be emitted after calling PSPDFKit.Instance.history.clear.

Example

Register a HistoryClearEvent

instance.addEventListener("history.clear", () => {
  console.log('History cleared.');
});

HistoryRedoEvent(event)

This event will be emitted after calling PSPDFKit.Instance.history.redo or after pressing the main toolbar Redo button, optionally available.

If provided, the listener callback will receive a PSPDFKit.HistoryChangeEvent object.

Parameters:
Name Type Description
event PSPDFKit.HistoryChangeEvent
Example

Register a HistoryRedoEvent

instance.addEventListener("history.redo", (historyRedoEvent) => {
  console.log(historyRedoEvent);
});

HistoryUndoEvent(event)

This event will be emitted after calling PSPDFKit.Instance.history.undo or after pressing the main toolbar Undo button, optionally available.

If provided, the listener callback will receive a PSPDFKit.HistoryChangeEvent object.

Parameters:
Name Type Description
event PSPDFKit.HistoryChangeEvent
Example

Register a HistoryUndoEvent

instance.addEventListener("history.undo", (historyUndoEvent) => {
  console.log(historyUndoEvent);
});

HistoryWillChangeEvent(event)

This event will be emitted before adding an annotation change to the actions history; if the event's preventDefault() method is called, the change will not be added and the action will not be undoable.

If provided, the listener callback will receive a PSPDFKit.HistoryWillChangeEvent object.

Parameters:
Name Type Description
event PSPDFKit.HistoryWillChangeEvent
Example

Register a HistoryWillChangeEvent

instance.addEventListener("history.willChange", (historyWillChangeEvent) => {
  console.log(historyWillChangeEvent);
});

InkSignatureChangeEvent()

This event will fire whenever the list of ink signatures is changed (either a signature was added, updated, or deleted).

Example

Register a InkSignatureChangeEvent

instance.addEventListener("inkSignatures.change", () => {
  console.log("ink signature list changed");
});

InkSignatureCreateEvent(annotation)

This event will fire whenever a signature is created and stored. storedSignatures.create payload returns null values for the annotation id and name. We return these values because the created signature is not attached to the document hence it isn't assigned an id or name. If you want to retrieve a complete list of values of the signature annotation we suggest to listen to the annotations.create event.

Parameters:
Name Type Description
annotation PSPDFKit.Annotations.InkAnnotation | PSPDFKit.Annotations.ImageAnnotation

The newly stored annotation.

Example

Register a InkSignatureCreateEvent

instance.addEventListener("inkSignatures.create", annotation => {
  console.log(annotation);
});

InkSignatureDeleteEvent(annotation)

This event will fire whenever a signature is deleted.

Parameters:
Name Type Description
annotation PSPDFKit.Annotations.InkAnnotation | PSPDFKit.Annotations.ImageAnnotation

The deleted annotation.

Example

Register a InkSignatureDeleteEvent

instance.addEventListener("inkSignatures.delete", annotation => {
  console.log(annotation);
});

InkSignatureUpdateEvent(annotations)

This event will fire whenever one ink signature is updated.

Parameters:
Name Type Description
annotations PSPDFKit.Immutable.List.<(PSPDFKit.Annotations.InkAnnotation|PSPDFKit.Annotations.ImageAnnotation)>

The list of updated annotations.

Example

Register a InkSignatureUpdateEvent

instance.addEventListener("inkSignatures.update", annotations => {
  console.log(annotations);
});

PagePressEvent(event)

This event will be emitted whenever a click on a page occurs that is not handled by any occluding page element (annotation, form, etc.).

This event internally uses the onpointerup event triggered by the browser. This is an implementation detail which we are documenting because it is useful to prevent the propagation of click events on custom overlay items. Please don't rely on this behavior if possible and use it wisely as it might break in future.

The parameter is a PSPDFKit.PagePressEvent.

Parameters:
Name Type Description
event PSPDFKit.PagePressEvent
Example

Register a PagePressEvent and get the point in PDF page coordinates.

instance.addEventListener("page.press", (event) => {
  console.log(event.point);
});

SaveStateChangeEvent(event)

This event will be emitted whenever document save state changes. This reflects changes to return value of PSPDFKit.Instance.hasUnsavedChanges.

The parameter is SaveStateChangeEvent.

Parameters:
Name Type Description
event SaveStateChangeEvent
Example

Register a SaveStateChangeEvent

instance.addEventListener("document.saveStateChange", (event) => {
  console.log(`Document has unsaved changes: ${event.hasUnsavedChanges}`);
});

SearchStateChangeEvent(searchState)

Whenever the search state changes, this event will fire with the latest state.

Parameters:
Name Type Description
searchState PSPDFKit.SearchState

The next search state.

Example

Register a SearchStateChangeEvent

instance.addEventListener("search.stateChange", (searchState) => {
  console.log(searchState.isFocused);
});

SearchStateUpdater(currentSearchState) → {PSPDFKit.SearchState}

This callback can be used in the setSearchState() method to do atomic updates to the current search state.

Parameters:
Name Type Description
currentSearchState PSPDFKit.SearchState
Returns:

The new search state.

Type
PSPDFKit.SearchState
Example

Use ES2015 arrow functions and the update callback to reduce boilerplate

instance.setSearchState(state => state.set("isFocused", true));

SearchTermChangeEvent(event)

This event will fire whenever the customer types in a new search term in the search UI. It can be used to plug the default search into your own search UI.

For an example, see PSPDFKit.SearchTermChangeEvent.

Parameters:
Name Type Description
event PSPDFKit.SearchTermChangeEvent

StampAnnotationTemplatesSetter(currentStampAnnotationTemplates) → {Array.<(PSPDFKit.Annotations.StampAnnotation|PSPDFKit.Annotations.ImageAnnotation)>}

This callback can be used in the setStampAnnotationTemplates() method to do atomic updates to the current stamp annotation templates.

Parameters:
Name Type Description
currentStampAnnotationTemplates Array.<(PSPDFKit.Annotations.StampAnnotation|PSPDFKit.Annotations.ImageAnnotation)>
Returns:

The new stamp and image annotation templates.

Type
Array.<(PSPDFKit.Annotations.StampAnnotation|PSPDFKit.Annotations.ImageAnnotation)>
Example

Use ES2015 arrow functions and the update callback to reduce boilerplate

instance.setStampAnnotationTemplates(stamps => {
  stamps.pop(); // removes the last template of the stamps array
  return stamps;
});

StoredSignatureChangeEvent()

This event will fire whenever the list of ink signatures is changed (either a signature was added, updated, or deleted).

Example

Register a StoredSignatureChangeEvent

instance.addEventListener("storedSignatures.change", () => {
  console.log("ink signature list changed");
});

StoredSignatureCreateEvent(annotation)

This event will fire whenever a signature is created and stored.

Parameters:
Name Type Description
annotation PSPDFKit.Annotations.InkAnnotation | PSPDFKit.Annotations.ImageAnnotation

The newly stored annotation.

Example

Register a StoredSignatureCreateEvent

instance.addEventListener("storedSignatures.create", annotation => {
  console.log(annotation);
});

StoredSignatureDeleteEvent(annotation)

This event will fire whenever a signature is deleted.

Parameters:
Name Type Description
annotation PSPDFKit.Annotations.InkAnnotation | PSPDFKit.Annotations.ImageAnnotation

The deleted annotation.

Example

Register a StoredSignatureDeleteEvent

instance.addEventListener("storedSignatures.delete", annotation => {
  console.log(annotation);
});

StoredSignatureUpdateEvent(annotations)

This event will fire whenever one ink signature is updated.

Parameters:
Name Type Description
annotations PSPDFKit.Immutable.List.<(PSPDFKit.Annotations.InkAnnotation|PSPDFKit.Annotations.ImageAnnotation)>

The list of updated annotations.

Example

Register a StoredSignatureUpdateEvent

instance.addEventListener("storedSignatures.update", annotations => {
  console.log(annotations);
});

StoredSignaturesSetter(currentStoredSignatures) → {PSPDFKit.Immutable.List.<(PSPDFKit.Annotations.InkAnnotation|PSPDFKit.Annotations.ImageAnnotation)>}

This callback can be used in the setStoredSignatures() method to do atomic updates to the current list of signatures.

Parameters:
Name Type Description
currentStoredSignatures PSPDFKit.Immutable.List.<(PSPDFKit.Annotations.InkAnnotation|PSPDFKit.Annotations.ImageAnnotation)>
Returns:

The new signatures list.

Type
PSPDFKit.Immutable.List.<(PSPDFKit.Annotations.InkAnnotation|PSPDFKit.Annotations.ImageAnnotation)>
Example

Use ES2015 arrow functions and the update callback to reduce boilerplate

instance.setStoredSignatures(signatures => {
  signatures.push(
    new PSPDFKit.Annotations.InkAnnotation({
      lines: ...,
      boundingBox: ...,
    })
  );
  return signatures;
});

TabOrderUpdater(tabOrderedAnnotations) → {Array.<string>}

This callback can be used in the setViewState() method to do atomic updates to the current view state.

Parameters:
Name Type Description
tabOrderedAnnotations Array.<PSPDFKit.AnnotationsUnion>

Annotations ordered by the current tab order.

Returns:

Annotations IDs ordered following the new tab order.

Type
Array.<string>
Example

Use ES2015 arrow functions and the update callback to reduce boilerplate

// Sort page 0 annotations by their top position
instance.setPageTabOrder(
  0,
  currentTabOrderedAnnotations => currentTabOrderedAnnotations
    .sort((a, b) => a.boundingBox.top - b.boundingBox.top)
    .map(annotation => annotation.id)
);

TextLinePressEvent(event)

This event will be emitted whenever a click on a text line occurs that is not handled by any occluding page element (annotation, form, etc.).

The parameter is a PSPDFKit.TextLinePressEvent.

Parameters:
Name Type Description
event PSPDFKit.TextLinePressEvent
Example

Register a TextLinePressEvent and get the point in PDF page coordinates.

instance.addEventListener("textLine.press", (event) => {
  console.log(event.point);
});

TextSelectionChangeEvent(textSelectionnullable)

Whenever the text selection changes, this event will fire with the latest selection.

textSelection might be null when the selection was cleared.

Parameters:
Name Type Attributes Description
textSelection PSPDFKit.TextSelection <nullable>

The new text selection, if any.

Example

Register a TextSelectionChangeEvent

instance.addEventListener("textSelection.change", (textSelection) => {
  if (textSelection) {
    console.log("text is selected");
  } else {
    console.log("no text is selected");
  }
});

ToolbarItemsSetter(currentToolbarItems) → {Array.<PSPDFKit.ToolbarItem>}

This callback can be used in the setToolbarItems() method to do atomic updates to the current toolbar items.

Parameters:
Name Type Description
currentToolbarItems Array.<PSPDFKit.ToolbarItem>
Returns:

The new toolbar items.

Type
Array.<PSPDFKit.ToolbarItem>
Example

Use ES2015 arrow functions and the update callback to reduce boilerplate

instance.setToolbarItems(items => {
  items.push({
    type: "custom",
    title: "My Custom Button",
    onPress(){
      alert("hello");
    }
  });
  return items;
});

ViewStateChangeEvent(viewState, previousViewState)

This event will be emitted whenever the current view state changes either by the user (via clicking the UI) or via setViewState(). It will be called after other view state specific events. If, for example, the page index changes, PSPDFKit.Instance~ViewStateCurrentPageIndexChangeEvent will emit first.

If you update multiple properties at once, this event will only be dispatched once.

The callback takes the current PSPDFKit.ViewState as first argument, and the previous PSPDFKit.ViewState as second.

Parameters:
Name Type Description
viewState PSPDFKit.ViewState

The new view state

previousViewState PSPDFKit.ViewState

The previous view state

Examples

Register a ViewStateChangeEvent

instance.addEventListener("viewState.change", (viewState, previousViewState) => {
  console.log(previousViewState.toJS());
  console.log(viewState.toJS());
});

Will be emitted after specific events

instance.addEventListener("viewState.currentPageIndex.change", () => console.log("first"));
instance.addEventListener("viewState.change", () => console.log("second"));

ViewStateCurrentPageIndexChangeEvent(pageIndex)

This event will be emitted whenever the current page index changes. It can be used to track the current view of a user.

Parameters:
Name Type Description
pageIndex number

The page index of the page that's currently visible. If there is more than one page visible this will return the page that is using the most space in the viewport. pageIndex is zero-based and has a maximum value of totalPageCount - 1

Example

Register a ViewStateCurrentPageIndexChangeEvent

instance.addEventListener("viewState.currentPageIndex.change", (pageIndex) => {
  console.log(pageIndex);
});

ViewStateUpdater(currentViewState) → {PSPDFKit.ViewState}

This callback can be used in the setViewState() method to do atomic updates to the current view state.

Parameters:
Name Type Description
currentViewState PSPDFKit.ViewState
Returns:

The new view state.

Type
PSPDFKit.ViewState
Example

Use ES2015 arrow functions and the update callback to reduce boilerplate

instance.setViewState(state => state.set("currentPageIndex", 2));

ViewStateZoomChangeEvent(zoom)

This event will be emitted whenever the zoom level or the zoom mode changes. This could either be a number multiplier or a distinct zoom mode.

Parameters:
Name Type Description
zoom PSPDFKit.ZoomMode | number

The new zoom level or zoom mode.

Example

Register a ViewStateZoomChangeEvent

instance.addEventListener("viewState.zoom.change", (zoom) => {
  console.log(zoom);
});