Class: Instance

PSPDFKit.Instance

A mounted document instance.

You can generate an instance by using PSPDFKit.load.

Members

Methods

Type Definitions




Members

(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

Access the document 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:
  • Document
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) currentZoomLevel: number

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

Type:
  • number

(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.

Type:
  • number

(readonly) minimumZoomLevel: number

The minimum zoom level. This value depends on the current viewport and page dimensions.

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) 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.updateViewState 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:

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
}

createAnnotation(annotation) → {Promise.<PSPDFKit.Annotations.Annotation>}

Creates a new annotation and assigns an ID. If you need to ensure that that the annotation is persisted by the annotation provider, please refer to: PSPDFKit.Instance#ensureAnnotationSaved.

This method returns a promise that will resolve to the annotation record with the local ID set.

New annotations will be saved to the annotation provider and made visible in the UI instantly.

Parameters:
Name Type Description
annotation PSPDFKit.Annotations.Annotation

The annotation that should be created.

Throws:

Will throw an error when supplied annotation already has an ID.

Type
PSPDFKit.Error
Returns:

A promise that resolves to the annotation with the ID set.

Type
Promise.<PSPDFKit.Annotations.Annotation>
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.createAnnotation(annotation).then(function(createdAnnotation) {
    console.log(createdAnnotation);
  });
})

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);
  });
})

createBookmark(bookmark) → {Promise.<PSPDFKit.Bookmark>}

Creates a new bookmark and assigns an ID. If you need to ensure that that the bookmark is persisted by the bookmark provider, please refer to: PSPDFKit.Instance#ensureBookmarkSaved.

This method returns a promise that will resolve to the bookmark record with the local ID set.

New bookmarks will be saved to the bookmark provider and made visible in the UI instantly.

Parameters:
Name Type Description
bookmark PSPDFKit.Bookmark

The bookmark that should be created.

Throws:

Will throw an error when supplied bookmark already has an ID.

Type
PSPDFKit.Error
Returns:

A promise that resolves to the bookmark with the ID set.

Type
Promise.<PSPDFKit.Bookmark>
Example
PSPDFKit.load(configuration).then((instance) => {
  const bookmark = new PSPDFKit.Bookmark({
    name: "test",
    action: new PSPDFKit.Actions.URIAction({
      uri: "https://example.com"
    })
  });
  instance.createBookmark(bookmark).then(function(createdBookmark) {
    console.log(createdBookmark);
  });
})

deleteAnnotation(annotationId) → {Promise.<void>}

Deletes an annotation. This can be called with an annotation ID returned from PSPDFKit.Instance#annotations or PSPDFKit.Instance#createAnnotation.

This method returns a promise that will resolve to undefined.

Deleted annotations will be saved to the annotation provider and made visible in the UI instantly.

Parameters:
Name Type Description
annotationId number

The ID of the annotation you want to delete

Throws:

Will throw an error when supplied ID is not a valid annotation ID.

Type
PSPDFKit.Error
Returns:

A promise that resolves to undefined.

Type
Promise.<void>
Example
PSPDFKit.load(configuration).then(function(instance) {
  instance.deleteAnnotations(1).then(function() {
    instance.annotations.has(1); // => false
  })
})

deleteBookmark(bookmarkId) → {Promise.<void>}

Deletes a bookmark. This can be called with a bookmark ID returned from PSPDFKit.Instance#.getBookmarks or PSPDFKit.Instance#createBookmark.

This method returns a promise that will resolve to undefined.

Deleted bookmarks will be saved to the bookmark provider and made visible in the UI instantly.

Parameters:
Name Type Description
bookmarkId number

The ID of the bookmark you want to delete

Throws:

Will throw an error when supplied ID is not a valid bookmark ID.

Type
PSPDFKit.Error
Returns:

A promise that resolves to undefined.

Type
Promise.<void>
Example
PSPDFKit.load(configuration).then(function(instance) {
  instance.deleteBookmark(1).then(function() {
    instance.getBookmarks().has(1); // => false
  })
})

ensureAnnotationSaved(annotation) → {Promise.<PSPDFKit.Annotations.Annotation>}

Ensures that the annotation has been saved by the annotation provider and returns the current persisted state of the annotation.

This method returns a promise that will resolve to an PSPDFKit.Annotations.Annotation.

Parameters:
Name Type Description
annotation PSPDFKit.Annotations.Annotation

The annotation that needs ensuring that it is persisted by AnnotationProvider

Throws:

Will throw an error when supplied annotation has no ID.

Type
PSPDFKit.Error
Returns:

A promise that resolves to the current, persisted state of the annotation.

Type
Promise.<PSPDFKit.Annotations.Annotation>
Example
PSPDFKit.load(configuration).then(function(instance) {
  instance.createAnnotation(newAnnotation)
    .then(instance.ensureAnnotationSaved)
    .then(function() {
      console.log('Annotation persisted by annotation provider');
    });
});

ensureBookmarkSaved(bookmark) → {Promise.<PSPDFKit.Bookmark>}

Ensures that the bookmark has been saved by the bookmark provider and returns the current persisted state of the bookmark.

This method returns a promise that will resolve to an PSPDFKit.Bookmark.

Parameters:
Name Type Description
bookmark PSPDFKit.Bookmark

The bookmark that needs ensuring that it is persisted by BookmarkProvider

Throws:

Will throw an error when supplied bookmark has no ID.

Type
PSPDFKit.Error
Returns:

A promise that resolves to the current, persisted state of the bookmark.

Type
Promise.<PSPDFKit.Bookmark>
Example
PSPDFKit.load(configuration).then(function(instance) {
  instance.createBookmark(newBookmark)
    .then(instance.ensureBookmarkSaved)
    .then(function() {
      console.log('Bookmark persisted by bookmark provider');
    });
});

exportInstantJSON() → {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.

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

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(...);
});

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

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

Parameters:
Name Type Description
options 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.
Returns:

The binary contents of the PDF.

Type
Promise.<ArrayBuffer>
Examples

Export the PDF content

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

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

instance.exportPDF().then(function (buffer) {
  let a = document.createElement("a");
  let blob = new Blob([buffer], { type: "application/pdf" });
  let objectUrl = window.URL.createObjectURL(blob);
  a.href = objectUrl;
  a.style = "display: none";
  a.download = "download.pdf";
  document.body.appendChild(a);
  a.click();
  window.URL.revokeObjectURL(objectUrl);
});

exportXFDF() → {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.

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.<PSPDFKit.Annotations.Annotation>>}

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 ocurred.
  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.<PSPDFKit.Annotations.Annotation>>
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.Annotation.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;
})

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

Fetches an attachment based on its ID.

Parameters:
Name Type Description
attachmentId string

The ID of the attachments 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.Bookmarks 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;
})

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>>

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;
})

getFormFieldValues() → {Object}

Returns a simplified object that contains all form fields 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>.

Returns:

A simplified object that contains all form field values.

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

getInkSignatures() → {Promise.<PSPDFKit.Immutable.List.<PSPDFKit.Annotations.InkAnnotation>>}

Returns a copy of the available ink signatures. Signatures are Ink 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#populateInkAnnotation to retrieve the initial list of annotations.

Returns:

Promise that resolves with an Immutable list of InkSignatures

Type
Promise.<PSPDFKit.Immutable.List.<PSPDFKit.Annotations.InkAnnotation>>
Example

Retrieve the signatures and convert them to JSON

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

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);

getSelectedAnnotation() → (nullable) {PSPDFKit.Annotations.Annotation}

If an annotation is currently selected (and as well being either created or editable), this function will return the annotation.

Returns:

annotation

Type
PSPDFKit.Annotations.Annotation

hasUnsavedAnnotations() → {boolean}

Returns true if annotations are not yet sent to the server. This can be used in combination with PSPDFKit.Configuration.autoSaveMode to implement fine grained synchronization controls.

Whenever annotations are forwarded to the server (for example, when calling PSPDFKit.Instance#saveAnnotations), the method will return false again.

Returns:

Whether unsaved annotations are present or not.

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

hasUnsavedBookmarks() → {boolean}

Returns true if bookmarks are not yet sent to the server. This can be used in combination with PSPDFKit.Configuration.autoSaveMode to implement fine grained synchronization controls.

Whenever bookmarks are forwarded to the server (for example, when calling PSPDFKit.Instance#saveBookmarks), the method will return false again.

Returns:

Whether unsaved bookmarks are present or not.

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

hasUnsavedFormFieldValues() → {boolean}

Returns true if form field values are not yet sent to the server. This can be used in combination with PSPDFKit.Configuration.autoSaveMode to implement fine grained synchronization controls.

Whenever form field values are forwarded to the server (for example, when calling PSPDFKit.Instance#setFormFieldValues), the method will return false again.

Returns:

Whether unsaved form field values are present or not.

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

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(printModenullable)

Print the document programmatically.

Parameters:
Name Type Attributes Description
printMode PSPDFKit.PrintMode <nullable>

Optional print mode. See PSPDFKit.PrintMode.

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 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

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 pageIndex renders a page of a PDF document and returns the result as ArrayBuffer. This can be used as thumbnail.

It also requires one of width or height (but not both) to be included in the argument, each has to have a value in the interval (0; 5000]. The other dimension will be calculated based on the aspect ration of the document.

This endpoint 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 Object | Object

The width or height of the the resulting image. The other dimension will be calculated to keep the same aspect ratio.

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: 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 PDF document or the page of the provided pageIndex. This can be used as thumbnail.

It also requires one of width or height (but not both) to be included in the argument, each has to have a value in the interval (0; 5000]. The other dimension will be calculated based on the aspect ratio of the page.

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.

Parameters:
Name Type Description
dimension Object | Object

The width or height of the the resulting image. The other dimension will be calculated to keep the same aspect ratio.

pageIndex number

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

Returns:

The image url.

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

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

instance.renderPageAsImageURL({ width: width }, 0).then(function(src) {
  const image = document.createElement('img');
  image.src = src
  document.body.appendChild(image)
});

saveAnnotations()

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

By choosing PSPDFKit.AutoSaveMode.DISABLED, nothing gets saved to the annotation provider automatically, but by calling saveAnnotations, 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.

Example
PSPDFKit.load(configuration).then((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.createAnnotation(annotation);

 instance.saveAnnotations(); // Now the annotation gets saved to the annotation provider.
})

saveBookmarks()

With PSPDFKit.AutoSaveMode it's possible to define when bookmarks are saved to the bookmark provider, but it's also possible to define the point to save bookmarks yourself.

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

Example
PSPDFKit.load(configuration).then((instance) => {
  const bookmark = new PSPDFKit.Bookmark({
    name: "test",
    action: new PSPDFKit.Actions.URIAction({
      uri: "https://example.com"
    })
  });

 instance.createBookmark(bookmark);

 instance.saveBookmarks(); // Now the bookmark gets saved to the bookmark provider.
})

saveFormFieldValues()

With PSPDFKit.AutoSaveMode it's possible to define when form field values get saved to the data provider, but it's also possible to define the point to save form fields yourself.

By choosing PSPDFKit.AutoSaveMode.DISABLED, nothing gets saved to the data provider automatically, but by calling saveFormFieldValues, 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.

Example
PSPDFKit.load(configuration).then((instance) => {
  instance.setFormFieldValues({ foo: "bar" });
  instance.saveFormFieldValues(); // Now the change gets saved to the data provider.
})

Queries the PDF backend for all search results of a given term.

Parameters:
Name Type Description
term string

The search term.

Returns:

Resolves to an immutable list of search results.

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

Search for all occurrences of `foo`

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

setAnnotationCreatorName(annotationCreatorNamenullable)

Sets the annoation 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 })

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);

setFormFieldValues(object)

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>.

Parameters:
Name Type Description
object Object

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

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

setInkSignatures(InkSignaturesOrFunction)

This method is used to update the ink 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 a new PSPDFKit.Annotations.InkAnnotations. . When you pass in a List of PSPDFKit.Annotations.InkAnnotation, 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 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 getInkSignatures() can't change in between. See: InkSignaturesSetter

When the application doesn't have signatures in store this method will invoke PSPDFKit.Configuration#populateInkAnnotation 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
InkSignaturesOrFunction Array.<PSPDFKit.ToolbarItem> | PSPDFKit.Instance~InkSignaturesSetter

Either a new array of InkSignatures 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.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());

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.

In order to work each locale requires its locale data to be defined in PSPDFKit.I18n.localeData. Locale data provide pluralization rules and relative-time formatting features. For furter details please refer to the locale data docs.

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 or its locale data don't exist.

Type
PSPDFKit.Error
Returns:

void Returns a promise that resolves once the locale data are loaded and the locale is set.

Type
Promise

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.

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);

setSelectedAnnotation(annotationOrAnnotationIdnullable)

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

Parameters:
Name Type Attributes Description
annotationOrAnnotationId PSPDFKit.Annotations.Annotation | 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.

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 an 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 ]);

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;
});

setViewState(viewStateOrFunction)

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
viewStateOrFunction 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)"
}

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) → {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 the text lines of the given page.

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

updateAnnotation(annotation) → {Promise.<PSPDFKit.Annotations.Annotation>}

Updates an annotation and changes its contents. This can be called with annotations returned from PSPDFKit.Instance#annotations or PSPDFKit.Instance#createAnnotation.

This method returns a promise that will resolve to the annotation record.

Updated annotations will be saved to the annotation provider and made visible in the UI instantly.

Parameters:
Name Type Description
annotation PSPDFKit.Annotations.Annotation

The annotation that should be updated.

Throws:

Will throw an error when supplied annotation has no ID.

Type
PSPDFKit.Error
Returns:

A promise that resolves to the annotation.

Type
Promise.<PSPDFKit.Annotations.Annotation>
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.updateAnnotation(editedAnnotation);

editedAnnotation === updatedAnnotation; // => true

updateBookmark(bookmark) → {Promise.<PSPDFKit.Bookmark>}

Updates a bookmark. This can be called with bookmarks returned from PSPDFKit.Instance#.getBookmarks or PSPDFKit.Instance#createBookmark.

This method returns a promise that will resolve to the bookmark record.

Updated bookmarks will be saved to the bookmark provider and made visible in the UI instantly.

Parameters:
Name Type Description
bookmark PSPDFKit.Bookmark

The bookmark that should be updated.

Throws:

Will throw an error when supplied bookmark has no ID.

Type
PSPDFKit.Error
Returns:

A promise that resolves to the bookmark.

Type
Promise.<PSPDFKit.Bookmark>
Example
const instance = await PSPDFKit.load(configuration);
// Get all the bookmarks
const bookmarks = instance.getBookmarks();
// Grab the first one
const bookmark = bookmarks.first();

const editedBookmark = bookmark.set("name", "joe");
const updatedBookmark = await instance.updateBookmark(editedBookmark);

editedBookmark === updatedBookmark; // => true

Type Definitions

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();
});

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#createAnnotation, PSPDFKit.Instance#updateAnnotation or PSPDFKit.Instance#deleteAnnotation.

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

Example

Register a AnnotationsChangeEvent

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

AnnotationsCreateEvent(createdAnnotations)

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

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

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

Register a AnnotationsCreateEvent

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

AnnotationsDeleteEvent(deletedAnnotations)

This event will be emitted whenever new annotations where 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.<PSPDFKit.Annotations.Annotation>
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", () => {
  // ...
});

AnnotationSelectionChangeEvent(annotationnullable)

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

Parameters:
Name Type Attributes Description
annotation PSPDFKit.Annotations.Annotation <nullable>

The newly selected annotation, if any.

Example

Register a AnnotationSelectionChangeEvent

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

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.<PSPDFKit.Annotations.Annotation>
Example

Register a AnnotationsLoadEvent

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

AnnotationsOnPressEvent(event)

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

The parameter is a PSPDFKit.AnnotationsOnPressEvent.

Parameters:
Name Type Description
event PSPDFKit.AnnotationsOnPressEvent
Example

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

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

AnnotationsUpdateEvent(updatedAnnotations)

This event will be emitted whenever new annotations where 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.<PSPDFKit.Annotations.Annotation>
Example

Register a AnnotationsUpdateEvent

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

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 where created (either via the public API or via the UI).

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

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 new bookmarks where deleted (either via the public API or via the UI).

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

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.Bookmarks.

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 new bookmarks where updated (either via the public API or via the UI).

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

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", () => {
  // ...
});

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());
});

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", () => {
  // ...
});

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 }) => {
  // ...
});

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.

Parameters:
Name Type Description
annotation PSPDFKit.Annotations.InkAnnotation

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

The deleted annotation.

Example

Register a InkSignatureDeleteEvent

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

InkSignaturesSetter(currentInkSignatures) → {PSPDFKit.Immutable.List.<PSPDFKit.Annotations.InkAnnotation>}

This callback can be used in the setInkSignatures() method to do atomic updates to the current list of ink signatures.

Parameters:
Name Type Description
currentInkSignatures PSPDFKit.Immutable.List.<PSPDFKit.Annotations.InkAnnotation>
Returns:

The new ink signatures list.

Type
PSPDFKit.Immutable.List.<PSPDFKit.Annotations.InkAnnotation>
Example

Use ES2015 arrow functions and the update callback to reduce boilerplate

instance.setInkSignatures(signatures => {
  signatures.push(
    new PSPDFKit.Annotations.InkAnnotation({
      lines: ...,
      boundingBox: ...,
    })
  );
  return signatures;
});

InkSignatureUpdateEvent(annotations)

This event will fire whenever one ink signature is updated.

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

The list of updated annotations.

Example

Register a InkSignatureUpdateEvent

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

PageOnPressEvent(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.).

The parameter is a PSPDFKit.PageOnPressEvent.

Parameters:
Name Type Description
event PSPDFKit.PageOnPressEvent
Example

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

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

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;
});

TextLineOnPressEvent(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.TextLineOnPressEvent.

Parameters:
Name Type Description
event PSPDFKit.TextLineOnPressEvent
Example

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

instance.addEventListener("textLine.onPress", (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)

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 view state as an argument.

Parameters:
Name Type Description
viewState PSPDFKit.ViewState

The new view state

Examples

Register a ViewStateChangeEvent

instance.addEventListener("viewState.change", (viewState) => {
  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));

ZoomChangeEvent(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 ZoomChangeEvent

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