Members
Methods
Type Definitions
Members
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:
- Immutable.Map.<string, PSPDFKit.InstantClient>
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();
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);
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;
Get the current active annotation preset ID
Type:
- string
The current zoom level. This will be either the number set in the PSPDFKit.ZoomState or calculated using the current PSPDFKit.ViewState.
Type:
- number
Returns the current locale for the application.
Type:
- string
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
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
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:
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:
- Array.<PSPDFKit.ToolbarItem>
Get the total number of pages for this document
Type:
- number
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
Aborts the current print job.
Throws:
-
This method will throw when printing is disabled or no printing is currently being processed.
- Type
- PSPDFKit.Error
This method is used to register event listeners for one of the following events:
viewState.change
viewState.currentPageIndex.change
viewState.zoom.change
annotations.load
annotations.change
annotations.create
annotations.update
annotations.delete
annotations.press
annotations.willSave
annotations.didSave
annotations.focus
annotations.blur
bookmarks.change
bookmarks.willSave
bookmarks.didSave
bookmarks.load
bookmarks.create
bookmarks.update
bookmarks.delete
document.change
formFieldValues.update
formFieldValues.willSave
formFieldValues.didSave
formFields.load
formFields.change
formFields.create
formFields.update
formFields.delete
formFields.willSave
formFields.didSave
forms.willSubmit
forms.didSubmit
inkSignatures.create
inkSignatures.update
inkSignatures.delete
inkSignatures.change
instant.connectedClients.change
instant.connectedClients.change
textSelection.change
annotationSelection.change
page.press
textLine.press
search.stateChange
search.termChange
document.change
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
}
Applies operations to the current document. If multiple operations are provided, each operation is performed on the resulting document from the previous operation.
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
}
]);
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.
Example
textAnnotation = instance.calculateFittingTextAnnotationBoundingBox(textAnnotation);
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);
});
})
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);
});
})
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);
});
})
Creates a form field.
Parameters:
Name | Type | Description |
---|---|---|
FormField |
FormField A FormField instance. |
Throws:
-
Will throw an error when supplied form field does not have a name.
- Type
- PSPDFKit.Error
Returns:
A promise that resolves to the form field.
- Type
- Promise.<PSPDFKit.FormFields.FormField>
Example
const widget = new PSPDFKit.Annotations.WidgetAnnotation({
pageIndex: 0,
formFieldName: "MyFormField",
boundingBox: new PSPDFKit.Geometry.Rect({
left: 100,
top: 75,
width: 200,
height: 80
})
});
instance.createAnnotation(widget)
.then(annotation => {
instance.createFormField(
new PSPDFKit.FormFields.TextFormField({
name: "MyFormField",
annotationIds: new PSPDFKit.Immutable.List([annotation.id])
});
)
.then(formField => {
console.log("Form field " + formField.name + " created")
});
})
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.
If the deleted annotation is a PSPDFKit.Annotations.WidgetAnnotation
(which can only be
deleted if the editable_forms
feature is present in the license, and the backend is using
a form editing 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 |
---|---|---|
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.deleteAnnotation(1).then(function() {
console.log("Annotation 1 deleted.");
});
});
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
})
})
Deletes a form field from the document. This method will also delete any widget annotations that may be associated with the form field.
Parameters:
Name | Type | Description |
---|---|---|
ID |
ID A FormField instance ID. |
Throws:
-
Will throw an error when a form field with the supplied ID does not exist.
- Type
- PSPDFKit.Error
Returns:
A promise that resolves to undefined
.
- Type
- Promise.<void>
Example
instance.getFormFields().then(formFields =>
// Deletes the form field
instance.deleteFormField(formFields.first().id);
);
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');
});
});
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');
});
});
Ensures that the form field has been saved by the form field provider and returns the current persisted state of the form field.
This method returns a promise that will resolve to a PSPDFKit.FormFields.FormField.
Parameters:
Name | Type | Description |
---|---|---|
formField |
PSPDFKit.FormFields.FormField | The form field that needs ensuring that it is persisted by FormFieldProvider |
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 form field.
- Type
- Promise.<PSPDFKit.FormFields.FormField>
Example
PSPDFKit.load(configuration).then(function(instance) {
instance.createFormField(newFormField)
.then(instance.ensureFormFieldSaved)
.then(function() {
console.log('Form field persisted by form field provider');
});
});
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(...);
});
Exports the PDF contents as an ArrayBuffer
. This can be used to download the PDF.
Parameters:
Name | Type | Description |
---|---|---|
options |
Object | Export options object:
|
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) {
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);
}
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);
}
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(...);
});
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:
- The user creates a new text annotation on a page.
- 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.
- Next, the user updates the color of the text by using the annotation toolbar. The annotation will still be invalid although a change ocurred.
- 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.
|
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;
})
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);
});
})
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;
})
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>>
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 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 }
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());
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);
If an annotation is currently selected (and as well being either created or editable), this function will return the annotation.
Returns:
annotation
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);
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
});
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
});
Returns true
if form fields 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 fields are forwarded to the server (for example, when calling
PSPDFKit.Instance#saveFormFields), the method will return false
again.
Returns:
Whether unsaved form fields are present or not.
- Type
- boolean
Example
PSPDFKit.load(configuration).then(function(instance) {
instance.hasUnsavedFormFields(); // => false
});
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
})
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 |
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);
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 |
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);
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 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
This method is used to remove an existing PSPDFKit.CustomOverlayItem.
Parameters:
Name | Type | Description |
---|---|---|
id |
string | The |
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);
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));
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);
});
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
instance.renderPageAsImageURL({ width: 400 }, 0).then(function(src) {
const image = document.createElement('img');
image.src = src
document.body.appendChild(image)
});
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.
Returns:
Promise that resolves once the annotations have been persisted.
- Type
- Promise.<void>
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.
})
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.
Returns:
Promise that resolves once the bookmarks have been persisted.
- Type
- Promise.<void>
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.
})
With PSPDFKit.AutoSaveMode it's possible to define when form fields get saved to the form field 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 form field
provider automatically, but by calling instance.saveFormFields()
, 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.
Before creating a form field, you should create the widget annotations that will be associated with it, and pass their 'ids' in the form field constructor, as in the following code.
Returns:
Promise that resolves once the form fields have been persisted.
- Type
- Promise.<void>
Example
PSPDFKit.load(configuration).then((instance) => {
const widget = new PSPDFKit.Annotations.WidgetAnnotation({
pageIndex: 0,
formFieldName: "MyFormField",
boundingBox: new PSPDFKit.Geometry.Rect({
left: 100,
top: 75,
width: 200,
height: 80
})
);
instance.createAnnotation(widget)
.then(annotation => {
instance.createFormField(
new PSPDFKit.FormFields.TextFormField({
name: "MyFormField",
annotationIds: new PSPDFKit.Immutable.List([annotation.id])
})
)
.then(() => {
instance.saveAnnotations(); // Save the form field's associated widget annotation.
instance.saveFormFields(); // Now the form field gets saved to the form field provider.
});
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.
Returns:
Promise that resolves once the values have been persisted.
- Type
- Promise.<void>
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. 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
|
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);
});
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> |
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 |
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 })
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),
);
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);
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 |
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.<PSPDFKit.Annotations.Annotation> |
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
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 |
PSPDFKit.Annotations.Annotation | string |
<nullable> |
The annotation
model or annotation ID you want to set as selected. If |
autoSelectText |
boolean |
<nullable> |
Whether the text should be automatically selected. |
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"],
});
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 |
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());
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");
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 further 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
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);
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 |
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 |
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 ]);
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 |
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;
});
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)"
}
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");
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.
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 |
Throws:
-
Will throw an error when the supplied arguments is not valid.
- Type
- PSPDFKit.Error
Returns:
The transformed point or rectangle.
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 |
Throws:
-
Will throw an error when the supplied arguments is not valid.
- Type
- PSPDFKit.Error
Returns:
The transformed point or rectangle.
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 |
Throws:
-
Will throw an error when the supplied arguments is not valid.
- Type
- PSPDFKit.Error
Returns:
The transformed point or rectangle.
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 |
Throws:
-
Will throw an error when the supplied arguments is not valid.
- Type
- PSPDFKit.Error
Returns:
The transformed point or rectangle.
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
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
Updates a form field. The provided form field should already be present in the view,
and therefore have an id
set.
It can also be used to change the annotation 'ids' associated with the form field. In this case, the new 'ids' must correspond with widget annotations already present in the view.
Parameters:
Name | Type | Description |
---|---|---|
FormField |
FormField A FormField instance. |
Throws:
-
Will throw an error when supplied form field has no name.
- Type
- PSPDFKit.Error
Returns:
A promise that resolves to the form field.
- Type
- Promise.<PSPDFKit.FormFields.FormField>
Example
instance.getFormFields().then(formFields =>
// Updates the form field's label
instance.updateFormField(formFields.first().set("label", "New label"));
);
Type Definitions
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;
});
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();
});
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, event.formField)
});
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 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", () => {
// ...
});
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);
});
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);
});
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", () => {
// ...
});
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");
}
});
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, event.formField)
});
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);
});
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";
. }
});
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);
});
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", () => {
// ...
});
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", () => {
// ...
});
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.Bookmarks.
Parameters:
Name | Type | Description |
---|---|---|
createdBookmarks |
PSPDFKit.Immutable.List.<PSPDFKit.Bookmark> |
Example
Register a BookmarksCreateEvent
instance.addEventListener("bookmarks.create", (createdBookmarks) => {
console.log(createdBookmarks);
});
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.Bookmarks.
Parameters:
Name | Type | Description |
---|---|---|
deletedBookmarks |
PSPDFKit.Immutable.List.<PSPDFKit.Bookmark> |
Example
Register a BookmarksDeleteEvent
instance.addEventListener("bookmarks.delete", (deletedBookmarks) => {
console.log(deletedBookmarks);
});
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", () => {
// ...
});
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);
});
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.Bookmarks.
Parameters:
Name | Type | Description |
---|---|---|
updatedBookmarks |
PSPDFKit.Immutable.List.<PSPDFKit.Bookmark> |
Example
Register a BookmarksUpdateEvent
instance.addEventListener("bookmarks.update", (updatedBookmarks) => {
console.log(updatedBookmarks);
});
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", () => {
// ...
});
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());
});
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) => {
// ...
});
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 }) => {
// ...
});
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#createFormField, PSPDFKit.Instance#updateFormField or PSPDFKit.Instance#deleteFormField.
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", () => {
// ...
});
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);
});
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);
});
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", () => {
// ...
});
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);
});
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);
});
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", () => {
// ...
});
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", () => {
// ...
});
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 => {
// ...
});
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", () => {
// ...
});
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 }) => {
// ...
});
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");
});
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);
});
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);
});
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.
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;
});
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);
});
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.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);
});
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);
});
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));
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 |
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.
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;
});
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);
});
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");
}
});
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;
});
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"));
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.
|
Example
Register a ViewStateCurrentPageIndexChangeEvent
instance.addEventListener("viewState.currentPageIndex.change", (pageIndex) => {
console.log(pageIndex);
});
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));
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);
});