Namespaces
Members
Methods
Type Definitions
Members
The current annotation creator name. This is set using instance.setAnnotationCreatorName()
.
Type:
- string | null
Returns a deep copy of the latest annotation presets. This value changes whenever the user interacts with PSPDFKit or whenever PSPDFKit.Instance.setAnnotationPresets is called.
Mutating this object will have no effect.
Type:
- Object.<string, PSPDFKit.AnnotationPreset>
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
instance.connectedClients.count();
instance.connectedClients.groupBy(c => c.userId).count();
instance.connectedClients.filter(c => !c.userId).count();
Access the shadow root object of the PSPDFKit for Web viewer. This can be used to quickly interact with elements (using our public CSS API) inside the viewer.
When the iframe fallback is set, this property provides access the document
object of
the PSPDFKit for Web viewer frame instead.
Type:
- Document | ShadowRoot
Example
instance.contentDocument.addEventListener("mouseup", handleMouseUp);
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 current PSPDFKit.ViewState or calculated using the PSPDFKit.ZoomMode.
Type:
- number
Whether to disable snapping to points when creating annotations for measurement tools
Type:
- boolean
Example
instance.setViewState(viewState => viewState.set('disablePointSnapping', true))
Returns a deep copy of the latest document editor footer items. This value changes whenever the user interacts with PSPDFKit or whenever PSPDFKit.Instance.setDocumentEditorFooterItems is called.
Mutating this array will have no effect.
Type:
Returns a deep copy of the latest document editor toolbar items. This value changes whenever the user interacts with PSPDFKit or whenever PSPDFKit.Instance.setDocumentEditorToolbarItems is called.
Mutating this array will have no effect.
Type:
Returns a deep copy of the latest editableAnnotationTypes. This value changes whenever PSPDFKit.Instance.setEditableAnnotationTypes is called.
Mutating this object will have no effect.
Type:
- PSPDFKit.Immutable.Set.<PSPDFKit.Annotation>
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 stamp and image annotation templates. This value changes whenever PSPDFKit.Instance#setStampAnnotationTemplates is called.
Mutating this array will have no effect.
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.setViewState is called.
When you want to keep a reference to the latest view state, you should always listen on the PSPDFKit.Instance~ViewStateChangeEvent to update your reference.
Type:
Type:
- number
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
annotationPresets.update
annotations.load
annotations.change
annotations.create
annotations.transform
annotations.update
annotations.delete
annotations.press
annotations.willSave
annotations.didSave
annotations.focus
annotations.blur
annotations.willChange
bookmarks.change
bookmarks.willSave
bookmarks.didSave
bookmarks.load
bookmarks.create
bookmarks.update
bookmarks.delete
comments.change
comments.willSave
comments.didSave
comments.load
comments.create
comments.update
comments.delete
document.change
document.saveStateChange
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
storedSignatures.create
storedSignatures.update
storedSignatures.delete
storedSignatures.change
instant.connectedClients.change
textSelection.change
annotationSelection.change
page.press
textLine.press
search.stateChange
search.termChange
history.undo
history.redo
history.change
history.willChange
history.clear
cropArea.changeStart
cropArea.changeStop
documentComparisonUI.start
documentComparisonUI.end
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
instance.addEventListener("viewState.change", (viewState) => {
console.log(viewState.toJS());
});
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. This API works only if you have the document editor component in your license.
Parameters:
Name | Type | Description |
---|---|---|
operations |
Array.<PSPDFKit.DocumentOperation> | Operations to be performed on the document. |
Returns:
Promise that resolves with an array of results.
- Type
- Promise.<void>
Example
instance
.applyOperations([
{
type: "rotatePages",
pageIndexes: [0],
rotateBy: 90
}
]);
Applies redactions to the current document. This will overwrite the document, removing content irreversibly.
In the process of redacting the content, all the redaction annotations will be removed. Any annotation that is either partially or completely covered by a redaction annotation will be deleted.
Returns:
Promise that resolves when the redactions has been applied.
- Type
- Promise.<void>
Example
instance.applyRedactions().then(function() {
console.log("The document has been redacted.");
});
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);
Compares documents based on the operations provided and returns an object containing the results and errors in the same order as the operations.
Parameters:
Name | Type | Description |
---|---|---|
operation |
ComparisonOperation | The comparison operations to be applied. |
comparisonDocuments |
ComparisonDocuments | Descriptors of the original and changed documents. |
Returns:
- A promise that resolves to results of the comparison.
- Type
- Promise.<DocumentComparisonResult>
Example
const operation = new PSPDFKit.ComparisonOperation("text", { numberOfContextWords: 2 });
const originalDocument = new PSPDFKit.DocumentDescriptor({ filePath: "path/to/original.pdf", pageIndexes: [0]});
const changedDocument = new PSPDFKit.DocumentDescriptor({ filePath: "path/to/changed.pdf", pageIndexes: [0]});
const comparisonDocuments = { originalDocument, changedDocument };
instance.compareDocuments(operation, comparisonDocuments)
.then((comparisonResults) => {
console.log(comparisonResults);
});
Creates new changes and assigns them IDs. If you need to ensure that changes are persisted by the backend, please refer to: PSPDFKit.Instance#ensureChangesSaved.
This method returns a promise that will resolve to an array of records with the local IDs set.
New changes will be made visible in the UI instantly.
Parameters:
Name | Type | Description |
---|---|---|
changes |
PSPDFKit.Change | Array.<PSPDFKit.Change> | List.<PSPDFKit.Change> | A single change or a list/array of changes that should be created. |
Returns:
A promise that resolves to an array of created changes or an error if some changes could not be created.
- Type
- Promise.<Array.<PSPDFKit.Change>>
Example
PSPDFKit.load(configuration).then(function(instance) {
const annotation = new PSPDFKit.Annotations.InkAnnotation({
pageIndex: 0,
lines: PSPDFKit.Immutable.List([
PSPDFKit.Immutable.List([
new PSPDFKit.Geometry.DrawingPoint({ x: 0, y: 0 }),
new PSPDFKit.Geometry.DrawingPoint({ x: 100, y: 100}),
])
])
});
instance.create(annotation).then(function(createdAnnotations) {
console.log(createdAnnotations);
});
})
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);
});
})
Searches in the PDF document and creates a redaction annotation for each search result. You can search for a text, regex or use one of the patterns we provide. See PSPDFKit.SearchPattern for the list of all the patterns we support.
Regex syntax:
- Standalone: JavaScript (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions).
- Server: ICU regular expression, a derivative of Perl regular expressions.
Notice that matches included when using one of the PSPDFKit.SearchPattern options might overfit the criteria (i.e. include false positive results). This might happen since we strive for including all positive results and avoid data loss. Make sure to review the matches found.
Note for multiline regular expressions that document text lines end with CRLF (\r\n
).
Regular expressions that follow the JavaScript syntax are matched in a similar way to the RegExp.prototype.exec()
method (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec), but ignoring capturing groups, that is, this function only returns full string matches.
Parameters:
Name | Type | Description |
---|---|---|
term |
string | PSPDFKit.SearchPattern | The text, regex or pattern you want to search for. |
options |
object | Search options object:
|
Returns:
Promise that resolves when the redaction annotations have been created. Returns a list of new Redaction Annotation IDs.
- Type
- Promise.<PSPDFKit.Immutable.List.<string>>
Example
instance.createRedactionsBySearch(PSPDFKit.SearchPattern.CREDIT_CARD_NUMBER, {
searchType: PSPDFKit.SearchType.PRESET,
searchInAnnotations: true,
annotationPreset: {
overlayText: 'Redacted'
}
}).then(function(ids) {
console.log("The following annotations have been added:", ids);
return instance.applyRedactions();
});
// We can add an "annotations.create" event listener and add custom logic based on the
// information for each of the newly created redaction annotations
const {RedactionAnnotation} = PSPDFKit.Annotations
instance.addEventListener("annotations.create", annotations => {
const redactions = annotations.filter(annot => annot instanceof RedactionAnnotation)
if (redactions.size > 0) {
console.log("Redactions: ", redactions.toJS())
}
});
Deletes a change. This can be called with a change ID.
If you need to ensure that changes are persisted by the backend, please refer to: PSPDFKit.Instance#ensureChangesSaved.
Deleted changes will be made visible in the UI instantly.
If the deleted change is a PSPDFKit.Annotations.WidgetAnnotation
(which can only be deleted if the Form Creator component is present in
the license, and the backend is using a Form Creator capable provider),
and the associated PSPDFKit.FormField
only includes that annotation in
its annotationIds
list, the form field will also be deleted.
If there are more widget annotations remaining in the annotationIds
list,
as could be the case for radio buttons, for example, the form field's
annotationIds
property will be updated by removing the deleted
annotation's id
from it.
Parameters:
Name | Type | Description |
---|---|---|
changeIds |
string | Array.<string> | List.<string> | A single id or a list/array of ids of changes that should be deleted. |
Returns:
A promise that resolves to an array of deleted changes or an error if some changes could not be deleted.
- Type
- Promise.<Array.<PSPDFKit.Change>>
Example
PSPDFKit.load(configuration).then(function(instance) {
instance.delete(1).then(function() {
console.log("Object with ID 1 deleted.");
});
});
If there are any annotations groups, this function will return all annotations groups. deleteAnnotationsGroup
Parameters:
Name | Type | Description |
---|---|---|
annotationGroupKey |
string | The annotation group key. |
Ensures that changes have been saved to the backend and returns the current persisted state of these changes.
This method returns a promise that will resolve to an array of Change.
Parameters:
Name | Type | Description |
---|---|---|
changes |
PSPDFKit.Change | Array.<PSPDFKit.Change> | List.<PSPDFKit.Change> | A single change or a list/array of changes to ensure saved. |
Returns:
A promise that resolves to an array of changes or an error if some changes could not be saved.
- Type
- Promise.<Array.<PSPDFKit.Change>>
Example
PSPDFKit.load(configuration).then(function(instance) {
instance.create(newAnnotation)
.then(instance.ensureChangesSaved)
.then(function() {
console.log('Annotation persisted by annotation provider');
});
});
Instant JSON can be used to instantiate a viewer with a diff that is applied to the raw PDF. This format can be used to store annotation and form field value changes on your server and conveniently instantiate the viewer with the same content at a later time.
Instead of storing the updated PDF, this serialization only contains a diff that is applied on top of the existing PDF and thus allows you to cache the PDF and avoid transferring a potentially large PDF all the time.
This method is used to export the current annotations as Instant JSON. Use PSPDFKit.Configuration#instantJSON to load it.
annotations
will follow the Instant Annotation JSON format specification.
formFieldValues
will follow the Instant Form Field Value JSON format specification.
Optionally a version
argument can be provided to specify the Instant JSON version to use for exported annotations.
For Server-Backed setups, only saved annotations will be exported.
Parameters:
Name | Type | Description |
---|---|---|
version |
number | Optional Instant JSON version for annotations. |
Returns:
Instant JSON as a plain JavaScript object.
- Type
- Promise.<object>
Example
instance.exportInstantJSON().then(function (instantJSON) {
// Persist it to a server
fetch("https://example.com/annotations", {
"Content-Type": "application/json",
method: "POST",
body: JSON.stringify(instantJSON)
}).then(...);
});
Exports the document converted to the specified output format as an ArrayBuffer
. This can be used to download the resulting file.
An options
object should be passed to the method with a format
property
set to one of the supported conversion output formats: PSPDFKit.OfficeDocumentFormat.
Parameters:
Name | Type | Description |
---|---|---|
options |
object | Export options object: |
format |
object.format | one of PSPDFKit.OfficeDocumentFormat values. |
Returns:
The binary contents of the PDF.
- Type
- Promise.<ArrayBuffer>
Example
instance.exportOffice({ format: PSPDFKit.OfficeDocumentFormat.docx })
.then(function (buffer) {
const blob = new Blob([buffer], { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" });
const objectUrl = window.URL.createObjectURL(blob);
downloadPdf(objectUrl);
window.URL.revokeObjectURL(objectUrl);
});
function downloadPdf(blob) {
const a = document.createElement("a");
a.href = blob;
a.style.display = "none";
a.download = "download.docx";
a.setAttribute("download", "download.docx");
document.body.append(a);
a.click();
a.remove();
}
Exports the PDF contents as an ArrayBuffer
. This can be used to download the PDF.
An options
object can be passed to the method with the following flags:
flatten
, which will visually embed annotations and form fields in the document and remove them from the document's data.incremental
, which will force the document to be incrementally saved iftrue
.excludeAnnotations
, which will exclude annotations from the exported document.saveForPrinting
, which will exclude annotations that have thenoPrint
flag set totrue
from the exported document (Standalone only);includeComments
, which will include comments in the exported document (Server-Backed only).permissions
, which protects the PDF with a password.outputFormat
, which allows you to export a PDF in PDF/A format.optimize
, which allows optimization of the document to be exported (Server-Backed only).
If the document is digitally signed and the license includes the Digital Signatures component, the method will export the document incrementally saved by default, so as not to corrupt signed data. Otherwise, it will be exported as fully saved by default.
It's not possible to use flatten
and incremental
both set to true
at the same time,
as flattening is a destructive operation that will necessarily modify the provided document.
Please see this guide article for more information and examples.
Parameters:
Name | Type | Description |
---|---|---|
flags |
object | Export options object:
Instead of a boolean value you can pass your own object ith custom values for the properties above. Parameters
Defaults to
Otherwise, you can pass the above options object customised with your own values instead of a boolean value. |
Returns:
The binary contents of the PDF.
- Type
- Promise.<ArrayBuffer>
Examples
instance.exportPDF().then(function (buffer) {
buffer; // => ArrayBuffer
});
instance.exportPDF({
permissions: {
userPassword: "123",
ownerPassword: "123",
documentPermissions: [PSPDFKit.DocumentPermissions.annotationsAndForms]
}
}).then(function (buffer) {
buffer; // => ArrayBuffer
});
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
const operations = [
{
type: "rotatePages",
pageIndexes: [0],
rotateBy: 90
}
];
instance.exportPDFWithOperations(operations).then(function (buffer) {
buffer; // => ArrayBuffer
});
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.
Parameters:
Name | Type | Description |
---|---|---|
ignorePageRotation |
boolean | Optional flag to ignore page rotation when exporting XFDF, by default false. This means that the exported XFDF will contain the annotations in the same orientation as the page and if you import this XFDF using PSPDFKit.Configuration#XFDFIgnorePageRotation the annotations will be imported in the same orientation no matter the page rotation. |
Returns:
XFDF as a plain text.
- Type
- Promise.<string>
Example
instance.exportXFDF().then(function (xmlString) {
// Persist it to a server
fetch("https://example.com/annotations", {
"Content-Type": "application/vnd.adobe.xfdf",
method: "POST",
body: xmlString
}).then(...);
});
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 occurred.
- 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.<AnnotationsUnion>>
Example
instance.getAnnotations(0).then(function (annotations) {
annotations.forEach(annotation => {
console.log(annotation.pageIndex);
});
// Filter annotations by type
annotations.filter(annotation => {
return annotation instanceof PSPDFKit.Annotations.InkAnnotation;
})
// Filter annotations at a specific point
const pointInFirstPage = new PSPDFKit.Geometry.Point({ x: 20, y: 30 });
const annotationsAtPointInPage = annotationsOnFirstPage.filter(annotation => {
return annotation.boundingBox.isPointInside(pointInFirstPage);
});
// Get the number of currently loaded annotations
const totalAnnotations = annotations.size;
})
This function will return all annotations groups, if there are any annotations groups.
Returns:
annotations groups
- Type
- PSPDFKit.Immutable.Map.<string, Record.<string, PSPDFKit.Immutable.Set.<ID>>>
Fetches an attachment or an embedded file based on its ID.
Parameters:
Name | Type | Description |
---|---|---|
attachmentId |
string | The ID of the attachments or embedded files that should be fetched. |
Throws:
-
Will throw an error when the file can not be read.
- Type
- PSPDFKit.Error
Returns:
A promise that resolves to the attachment data.
- Type
- Promise.<?Blob>
Example
PSPDFKit.load(configuration).then(function(instance) {
instance.getAttachment("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad").then(function(image) {
console.log(image);
});
})
Returns a PSPDFKit.Immutable.List of PSPDFKit.Bookmark for the current document.
The list contains an immutable snapshot of the currently available bookmarks in the UI for the page.
When you want to keep a reference to the latest bookmarks, you can listen for PSPDFKit.Instance~BookmarksChangeEvent, PSPDFKit.Instance~BookmarksWillSaveEvent, or PSPDFKit.Instance~BookmarksDidSaveEvent to update your reference.
Returns:
Resolves to bookmarks for the given page.
- Type
- Promise.<PSPDFKit.Immutable.List.<PSPDFKit.Bookmark>>
Example
instance.getBookmarks().then(function (bookmarks) {
bookmarks.forEach(bookmark => {
console.log(bookmark.name);
});
// Get the number of currently loaded bookmarks
const totalBookmarks = bookmarks.size;
})
Returns a PSPDFKit.Immutable.List of PSPDFKit.Comment for the current document.
The list contains an immutable snapshot of the currently available comments in the UI.
When you want to keep a reference to the latest comments, you can listen for PSPDFKit.Instance~CommentsChangeEvent.
Returns:
Resolves to comments.
- Type
- Promise.<PSPDFKit.Immutable.List.<PSPDFKit.Comment>>
Example
instance.getComments().then(function (comments) {
comments.forEach(comment => {
console.log(comment.text);
});
// Get the number of currently loaded comments
const totalComments = comments.size;
})
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 the current PSPDFKit.DocumentPermissions of the document.
Returns:
A Promise resolving to an object containing the document permissions keys along with their status (true
or false
).
- Type
- Promise.<Object.<string, boolean>>
Example
const permissions = await instance.getDocumentPermissions();
Returns a list containing the information of all the embedded files in the PDF.
If you want to get the content of a particular embedded file, you can use PSPDFKit.Instance#getAttachment
const embeddedFiles = await instance.getEmbeddedFiles()
const fileContent = await instance.getAttachment(embeddedFiles.get(0).attachmentId)
Returns:
List of embedded files in the document with their individual information.
- Type
- Promise.<PSPDFKit.Immutable.List.<PSPDFKit.EmbeddedFile>>
Example
const embeddedFilesInfo = await instance.getEmbeddedFiles();
Returns a simplified object that contains all form fields currently loaded and maps to their values. This object can be used to serialize form field values.
Values can be of type null
, string
, or Array.<string>
.
This method does not check if all the form fields have been loaded. If you want to make sure that the all the document's form field values are retrieved, you have to make sure that the form fields have been retrieved first.
Returns:
A simplified object that contains all form field values.
- Type
- object
Example
await instance.getFormFields()
const formFieldValues = instance.getFormFieldValues();
console.log(formFieldValues); // => { textField: 'Text Value', checkBoxField: ['A', 'B'], buttonField: null }
Returns a PSPDFKit.Immutable.List of all PSPDFKit.FormFields for this document.
Returns:
Resolves to a list of all form fields.
- Type
- Promise.<PSPDFKit.Immutable.List.<PSPDFKit.FormFields.FormField>>
Example
instance.getFormFields().then(formFields => {
formFields.forEach(formField => {
console.log(formField.name);
});
// Filter form fields by type
formFields.filter(formField => (
formField instanceof PSPDFKit.FormFields.TextFormField
));
// Get the total number of form fields
const totalFormFields = formFields.size;
})
Returns a copy of the available stored signatures. Signatures are ink and image annotations and therefore can be converted to JavaScript objects with PSPDFKit.Annotations.toSerializableObject.
When the application doesn't have signatures in store this method will invoke PSPDFKit.Configuration#populateStoredSignatures to retrieve the initial list of annotations.
- Deprecated
Returns:
Promise that resolves with an Immutable list of signatures
- Type
- Promise.<PSPDFKit.Immutable.List.<(PSPDFKit.Annotations.InkAnnotation|PSPDFKit.Annotations.ImageAnnotation)>>
Example
instance
.getInkSignatures()
.then(signatures => signatures.map(PSPDFKit.Annotations.toSerializableObject).toJS());
Returns a list of OCG layers present in the document.
Returns:
A promise that resolves to
an Array
of PSPDFKit.Layer
- Type
- Promise.<Array.<PSPDFKit.Layer>>
Returns the current OCG layers visibility state.
OCG layers are groups of content in the document, that can be shown or hidden independently.
This method returns the current visibility state of the layers in the document as an object
with a visibleLayerIds
Array
that contains the list of layers identified by their ocgId
number, which are currently visible.
Returns:
A promise that resolves to a PSPDFKit.LayersVisibilityState
- Type
- Promise.<PSPDFKit.LayersVisibilityState>
Example
instance.getLayersVisibilityState().then(function (layersVisibilityState) {
console.log(layersVisibilityState); // => { visibleLayerIds: [1, 2, 3] }
});
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
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);
Returns a PSPDFKit.Immutable.List of PSPDFKit.Annotations for the given form field or annotation.
The list contains an immutable snapshot of the currently overlapping annotations for the argument.
If annotations for this page have not been loaded yet, the promise will resolve only after we have received all annotations.
Parameters:
Name | Type | Description |
---|---|---|
annotationOrFormField |
AnnotationsUnion | FormField | the annotation or the form field that needs to be checked for overlapping annotations. |
Returns:
Resolves to a list of the annotations that overlap the given argument.
- Type
- Promise.<PSPDFKit.Immutable.List.<AnnotationsUnion>>
Examples
get signature overlapping a signature form field
// The name of the field you want to check.
const formFieldName = "signature";
// First get all `FormFields` in the `Document`.
const formFields = await instance.getFormFields();
// Get a signature form with the specific name you want.
const field = formFields.find(
(formField) =>
formField.name === formFieldName && formField instanceof PSPDFKit.FormFields.SignatureFormField
);
// Check if the signature form field has been signed
await instance.getOverlappingAnnotations(field);
// It will result in a list of annotations that overlaps the given signature form field.
// If no annotation overlaps the form field, the list will be empty.
get annotations overlapping an ink annotation
const annotations = instance.getAnnotations(0);
const inkAnnotation = annotations.find(
(annotation) =>
annotation instanceof PSPDFKit.Annotation.InkAnnotation
);
await instance.getOverlappingAnnotations(inkAnnotation);
// It will result in a list of annotations that overlaps the given signature form field.
// If no annotation overlaps the form field, the list will be empty.
*** Standalone only ***
This method is used to retrieve the tab order of annotations in a given page.
The tab order will be returned as an array of annotation IDs.
In the case of widget annotations associated to a radio form field, all the widgets
associated to the same form field are rendered next to the first one found
in the provided Array
of annotation IDs.
Parameters:
Name | Type | Description |
---|---|---|
pageIndex |
number |
Throws:
-
Will throw an error when the supplied page index is not a number.
- Type
- PSPDFKit.Error
Returns:
A promise that resolves to an ordered array of annotation IDs.
- Type
- Promise.<Array.<string>>
Example
instance.getPageTabOrder(0);
If multiple annotations are selected, this function will return the set of selected annotations.
Returns:
annotation
Gets the digital signatures validation information for all the signatures present in the current document. See PSPDFKit.SignaturesInfo.
Returns:
Promise that resolves with a PSPDFKit.SignaturesInfo.
- Type
- Promise.<PSPDFKit.SignaturesInfo>
Example
instance.getSignaturesInfo()
.then(signaturesInfo => {
console.log(signaturesInfo.status)
if(signaturesInfo.signatures) {
const invalidSignatures = signaturesInfo.signatures
.filter(signature => signature.signatureValidationStatus !== PSPDFKit.SignatureValidationStatus.valid);
console.log(invalidSignatures);
}
});
Additional information can be found in
this guide article.
Returns a copy of the available stored signatures. Signatures are ink and image annotations and therefore can be converted to JavaScript objects with PSPDFKit.Annotations.toSerializableObject.
When the application doesn't have signatures in store this method will invoke PSPDFKit.Configuration#populateStoredSignatures to retrieve the initial list of annotations.
Returns:
Promise that resolves with an Immutable list of signatures
- Type
- Promise.<PSPDFKit.Immutable.List.<(PSPDFKit.Annotations.InkAnnotation|PSPDFKit.Annotations.ImageAnnotation)>>
Example
instance
.getStoredSignatures()
.then(signatures => signatures.map(PSPDFKit.Annotations.toSerializableObject).toJS());
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
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);
Gets the current text selection in the document, if any.
Returns:
A promise that resolves to the
current text selection, or null
if no text is selected.
- Type
- Promise.<?PSPDFKit.TextSelection>
Example
const currentSelection = instance.getTextSelection();
if (currentSelection != null) {
const text = await currentSelection.getText();
alert(`Selection: '${text}'`);
}
Group annotations in the user interface.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
annotationsOrAnnotationsId |
PSPDFKit.Immutable.List.<(PSPDFKit.Annotations.Annotation|string)> |
<nullable> |
The annotations model or annotations IDs you want to be grouped. Annotations selected for grouping must be on the same page. Annotations that are already grouped will be removed from the previous group and added to the new one. |
Returns true
if any local changes are not yet saved. This can be used in combination with
PSPDFKit.Configuration.autoSaveMode to implement fine grained save controls.
Whenever changes are saved (for example, when calling PSPDFKit.Instance#save),
the method will return false
again.
Returns:
Whether unsaved changes are present or not.
- Type
- boolean
Example
PSPDFKit.load(configuration).then(function(instance) {
instance.hasUnsavedChanges(); // => false
});
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
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
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 | Description |
---|---|---|
options |
object | Print options object:
|
Throws:
-
This method will throw when printing is disabled, currently in process or when an invalid PSPDFKit.PrintMode was supplied.
- Type
- PSPDFKit.Error
This method is used to remove an existing PSPDFKit.CustomOverlayItem.
Parameters:
Name | Type | Description |
---|---|---|
id |
string | The |
Example
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
const callback = someFunction.bind(this)
instance.addEventListener("viewState.zoom.change", callback);
instance.removeEventListener("viewState.zoom.change", callback);
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 dimension
and pageIndex
renders a page of a document and returns the
result as ArrayBuffer
. This can be used as thumbnail.
You can specify a width or height (but not both at the same time) as the first dimension
argument, each accepts a value in the interval (0; 5000]
. The other dimension will be
calculated based on the aspect ratio of the document.
This method can be used to provide thumbnail images for your document list. You can use it
in a <canvas>
tag. The following example will load the cover of the loaded document with a
width of 400px
. We set the width of the <canvas>
tag to 200px
, so the image will be
sharp on high DPI screens.
Parameters:
Name | Type | Description | |||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
dimension |
The size of the resulting image. Only accepts either Properties
|
||||||||||
pageIndex |
number | The index of the page you want to have information about. |
Returns:
The raw image as bitmap.
- Type
- Promise.<ArrayBuffer>
Example
const pageWidth = instance.pageInfoForIndex(0).width;
const pageHeight = instance.pageInfoForIndex(0).height;
const width = 400;
const height = Math.round(width * pageHeight / pageWidth);
instance.renderPageAsArrayBuffer({ width }, 0).then(function(buffer) {
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
canvas.style.transformOrigin = "0 0";
canvas.style.transform = "scale(0.5)";
const imageView = new Uint8Array(buffer);
const ctx = canvas.getContext("2d");
const imageData = ctx.createImageData(width, height);
imageData.data.set(imageView);
ctx.putImageData(imageData, 0, 0);
document.body.appendChild(canvas);
});
Generates a URL to an image for the first page of a document or the page of the
provided pageIndex
. This can be used as thumbnail.
You can specify a width or height (but not both at the same time) as the first dimension
argument, each accepts a value in the interval (0; 5000]
. The other dimension will be
calculated based on the aspect ratio of the document.
This endpoint can be used to provide thumbnail images for your document list. You can use it
as a src
for an img
tag. The following example will load the cover of the loaded document with a
width of 400px
.
The returned URL is a Blob URL.
In order to prevent memory leaks, it's recommended to revoke the returned object URL once the image is no longer needed, as in the example.
Parameters:
Name | Type | Description | |||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
dimension |
The size of the resulting image. Only accepts either Properties
|
||||||||||
pageIndex |
number | The index of the page you want to have information about. |
Returns:
The image url.
- Type
- Promise.<string>
Example
let objectURL
instance.renderPageAsImageURL({ width: 400 }, 0).then(function(src) {
const image = document.createElement('img');
image.src = src;
objectURL = src;
document.body.appendChild(image);
});
// Once the image is no longer needed, we revoke the URL so that the associated
// Blob is released.
function callWhenTheImageIsNoLongerNeeded() {
// Is it an object URL?
if (objectURL.split("://")[0] === "blob") {
URL.revokeObjectURL(objectURL);
}
}
This method can be used to change the default group back to original after it was changed to
something else using instance.setGroup
.
This method is no-op if Collaboration Permissions is not enabled.
With PSPDFKit.AutoSaveMode it's possible to define when local changes get saved, but it's also possible to define the point to save changes yourself.
By choosing PSPDFKit.AutoSaveMode.DISABLED, nothing gets saved automatically, but
by calling save
, it's possible to manually trigger save. This can be useful when you want
to have full control when new changes get saved to your backend.
Returns:
Promise that resolves once all changes are saved on remote server (in case of server-based backend) or in local backend (in case of standalone). If changes could not be saved, rejects with PSPDFKit.SaveError.
- Type
- Promise.<void>
Example
PSPDFKit.load(configuration).then(async (instance) => {
const annotation = new PSPDFKit.Annotations.InkAnnotation({
pageIndex: 0,
lines: PSPDFKit.Immutable.List([
PSPDFKit.Immutable.List([
new PSPDFKit.Geometry.DrawingPoint({ x: 0, y: 0 }),
new PSPDFKit.Geometry.DrawingPoint({ x: 100, y: 100}),
])
])
});
await instance.create(annotation);
await instance.save(); // Now the annotation gets saved.
})
Queries the PDF backend for all search results of a given term. Search is case-insensitive and accented letters are ignored. The minimum query length for the term query to be performed can be retrieved from PSPDFKit.Instance#minQueryLength.
Shorter queries will throw an error.
Parameters:
Name | Type | Description | ||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
term |
string | The search term. |
||||||||||||||||||
options |
Optional parameters used for search operation. Properties
|
Returns:
Resolves to an immutable list of search results.
- Type
- Promise.<PSPDFKit.Immutable.List.<PSPDFKit.SearchResult>>
Examples
instance.search("foo").then(results => {
console.log(results.size);
});
instance.search("foo", { startPageIndex: 1, endPageIndex: 4 }).then(results => {
console.log(results.size);
});
instance.search("Q[a-z]+ck\\sC.*[tT]", { searchType: PSPDFKit.SearchType.REGEX }).then(results => {
console.log(results.size);
});
instance.search(PSPDFKit.SearchPattern.DATE, { searchType: PSPDFKit.SearchType.PATTERN }).then(results => {
console.log(results.size);
});
instance.search("he[a-z]+", { searchType: PSPDFKit.SearchType.REGEX, caseSensitive: false }).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
instance.setAnnotationPresets(newAnnotationPresets);
instance.annotationPresets === newAnnotationPresets; // => true
const myAnnotationPreset = {
dashedEllipse: {
strokeDashArray: [3, 3],
}
}
instance.setAnnotationPresets(annotationPresets => ({ ...annotationPresets, myAnnotationPreset })
You can use this callback to set/modify the toolbar items present in the annotation toolbar after the document has loaded.
The callback will receive the annotation which is being created or selected and based on it, you can have different annotation toolbars for different annotations.
You can do the following modifications using this API:
- Add new annotation toolbar items
- Remove existing annotation toolbar items
- Change the order of the existing annotation toolbar items
- Modify selected properties of the annotation toolbar items
You can also use the hasDesktopLayout
to determine if the current UI is being rendered on
mobile or desktop. Based on that, you can implement different designs for Desktop and Mobile.
This callback gets called every time the annotation toolbar is mounted.
Parameters:
Name | Type | Description |
---|---|---|
annotationToolbarItemsCallback |
PSPDFKit.AnnotationToolbarItemsCallback |
Example
instance.setAnnotationToolbarItems((annotation, { defaultAnnotationToolbarItems, hasDesktopLayout }) => {
const node = document.createElement('node')
node.innerText = "Custom Item"
const icon = `<svg xmlns="http://www.w3.org/2000/svg" height="24" width="24" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4" /></svg>`
return [{
id: "custom",
type: "custom",
node: node,
icon: icon,
className: 'Custom-Node',
onPress: () => alert("Custom item pressed!")
}, ...defaultAnnotationToolbarItems];
});
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
instance.setCurrentAnnotationPreset("ink");
instance.currentAnnotationPreset === "ink"; // => true
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
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);
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 |
Sets the current custom UI configuration. When this function is called with a new PSPDFKit.CustomUI object, all visible sidebars are immediately updated.
Parameters:
Name | Type | Description |
---|---|---|
customUIConfigurationOrCustomUIConfigurationSetter |
PSPDFKit.CustomUIConfiguration | PSPDFKit.Instance~CustomUIConfigurationSetter |
Standalone only
Enables or disables the document comparison UI.
When a PSPDFKit.DocumentComparisonConfiguration object is passed, the document comparison UI is mounted and initialized with the provided settings.
When null
is passed, the document comparison UI is hidden if it was being shown.
Parameters:
Name | Type | Description |
---|---|---|
documentComparisonConfiguration |
PSPDFKit.DocumentComparisonConfiguration | null | Initial document comparison configuration. |
Returns:
- Type
- Promise.<void>
Example
instance.setDocumentComparisonMode({
documentA: {
source: fetch("old-document.pdf").then(res => res.arrayBuffer())
},
documentB: {
source: fetch("old-document.pdf").then(res => res.arrayBuffer())
},
autoCompare: true
});
This method is used to update the document editor footer of the PDF editor. It makes it possible to add new items and edit or remove existing ones.
When you pass in an array
of PSPDFKit.DocumentEditorFooterItem, the current items will be immediately
updated. Calling this method is also idempotent.
If you pass in a function, it will be immediately invoked and will receive the current
array
of PSPDFKit.DocumentEditorFooterItem as argument. You can use this to modify the list based on its
current value. This type of update is guaranteed to be atomic - the value of currentDocumentEditorFooterItems
can't change in between.
See: DocumentEditorFooterItemsSetter
When one of the supplied PSPDFKit.DocumentEditorFooterItem is invalid, this method will throw an PSPDFKit.Error that contains a detailed error message.
Since items
is a regular JavaScript Array
of object literals it can be manipulated using
standard array methods like forEach
, map
, reduce
, splice
and so on.
Additionally you can use any 3rd party library for array manipulation like lodash
or just.
Parameters:
Name | Type | Description |
---|---|---|
documentEditorFooterItemsOrFunction |
Array.<PSPDFKit.DocumentEditorFooterItem> | PSPDFKit.Instance~DocumentEditorFooterItemsSetter | Either a
new |
Throws:
-
will throw an error when the supplied items array is not valid. This will also throw an error if you don not have document editor license.
- Type
- PSPDFKit.Error
Examples
instance.setDocumentEditorFooterItems(items => items.reverse());
instance.setDocumentEditorFooterItems(newItems);
instance.documentEditorFooterItems === newItems; // => true
const myButton = {
type: "custom",
id: "my-button",
onPress() {
alert("test");
},
};
This method is used to update the document editor toolbar of the PDF editor. It makes it possible to add new items and edit or remove existing ones.
When you pass in an array
of PSPDFKit.DocumentEditorToolbarItem, the current items will be immediately
updated. Calling this method is also idempotent.
If you pass in a function, it will be immediately invoked and will receive the current
array
of PSPDFKit.DocumentEditorToolbarItem as argument. You can use this to modify the list based on its
current value. This type of update is guaranteed to be atomic - the value of currentDocumentEditorToolbarItems
can't change in between.
See: DocumentEditorToolbarItemsSetter
When one of the supplied PSPDFKit.DocumentEditorToolbarItem is invalid, this method will throw an PSPDFKit.Error that contains a detailed error message.
Since items
is a regular JavaScript Array
of object literals it can be manipulated using
standard array methods like forEach
, map
, reduce
, splice
and so on.
Additionally you can use any 3rd party library for array manipulation like lodash
or just.
Parameters:
Name | Type | Description |
---|---|---|
documentEditorToolbarItemsOrFunction |
Array.<PSPDFKit.DocumentEditorToolbarItem> | PSPDFKit.Instance~DocumentEditorToolbarItemsSetter | Either a
new |
Throws:
-
will throw an error when the supplied items array is not valid. This will also throw an error if you don not have document editor license.
- Type
- PSPDFKit.Error
Examples
instance.setDocumentEditorToolbarItems(items => items.reverse());
instance.setDocumentEditorToolbarItems(newItems);
instance.documentEditorToolbarItems === newItems; // => true
const myButton = {
type: "custom",
id: "my-button",
onPress() {
alert("test");
},
};
Standalone only
Sets the document outline (table of content).
Parameters:
Name | Type | Description |
---|---|---|
outline |
PSPDFKit.Immutable.List.<PSPDFKit.OutlineElement> | The outline to set. |
Returns:
A promise that resolves when the outline has been set.
- Type
- Promise.<void>
This method is used to update the editable annotation types.
When one of the supplied PSPDFKit.Annotations.Annotation is invalid, this method will throw an PSPDFKit.Error that contains a detailed error message.
Parameters:
Name | Type | Description |
---|---|---|
editableAnnotationTypes |
Array.<AnnotationsUnion> |
Throws:
-
Will throw an error when the supplied array is not valid.
- Type
- PSPDFKit.Error
Example
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 |
AnnotationsUnion | 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>
. A null
value will reset
the form field to either null
, or its default value if available.
This method returns a Promise that resolves when all the form fields have been updated, so it should be awaited whenever you need to get or modify form fields immediately to ensure the form field value is synchronized.
Parameters:
Name | Type | Description |
---|---|---|
formFieldValues |
object | An object that contains the form field names that should be updated as keys and their value as values. |
Returns:
Resolves when the values have been set.
- Type
- Promise.<void>
Example
instance.setFormFieldValues({
textField: "New Value",
checkBoxField: ["B", "C"],
});
This method is used to update the group that will be used by default in all the newly created form-fields, comments and annotations. If you don't have permission to change the group, you will get error when you try to add an annotation, comment or form-field.
This method is no-op if Collaboration Permissions is not enabled.
Parameters:
Name | Type | Description |
---|---|---|
group |
string | The new group that you want to use for all the newly created form-fields, comments and annotations. |
This method is used to update the signatures list. It makes it possible to add new signatures and edit or remove existing ones.
Ink Signatures are Ink Annotations whose pageIndex
and boundingBox
is calculated at creation time.
When selected via UI such annotations are used as template to create new PSPDFKit.Annotations.InkAnnotations and PSPDFKit.Annotations.ImageAnnotations.
.
When you pass in a List of PSPDFKit.Annotations.InkAnnotation and PSPDFKit.Annotations.ImageAnnotation, the current list of signatures will be immediately
updated. Calling this method is also idempotent.
If you pass in a function, it will be invoked with the current List of PSPDFKit.Annotations.InkAnnotation and PSPDFKit.Annotations.ImageAnnotation as argument.
You can use this to modify the list based on its current value.
This type of update is guaranteed to be atomic - the value of getStoredSignatures()
can't change in between.
See: StoredSignaturesSetter
When the application doesn't have signatures in store this method will invoke PSPDFKit.Configuration#populateStoredSignatures to retrieve the initial list of annotations and it will pass it to your function.
When the list is invalid, this method will throw an PSPDFKit.Error that contains a detailed error message.
Parameters:
Name | Type | Description |
---|---|---|
StoredSignaturesOrFunction |
Array.<PSPDFKit.ToolbarItem> | PSPDFKit.Instance~StoredSignaturesSetter | Either a
new |
- Deprecated
Throws:
-
Will throw an error when the supplied items
array
is not valid. - Type
- PSPDFKit.Error
Examples
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) });
instance.setInkSignatures(signatures => signatures.reverse());
const signature = new PSPDFKit.Annotations.InkAnnotation({ lines: ..., boundingBox: ... });
instance.setInkSignatures(signatures => signatures.push(signature));
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
instance.setIsEditableAnnotation((annotation) => annotation.creatorName === "Alice");
This method is used to update the isEditableComment callback
When the supplied callback is invalid it will throw a PSPDFKit.Error that contains a detailed error message.
To learn more check this guide article.
Parameters:
Name | Type | Description |
---|---|---|
isEditableCommentCallback |
PSPDFKit.IsEditableCommentCallback |
Throws:
-
Will throw an error when the supplied array is not valid.
- Type
- PSPDFKit.Error
Example
instance.setIsEditableComment((comment) => comment.creatorName === myCurrentUser.name);
Sets the OCG visibility state.
This method takes an PSPDFKit.LayersVisibilityState object as an argument, which contains
a visibleLayerIds
Array
that contains the list of layers identified by their ocgId
, and
makes them visible, hiding any other layers not included in the Array
.
Parameters:
Name | Type | Description |
---|---|---|
layersVisibilityState |
PSPDFKit.LayersVisibilityState | The OCG visibility state to set. |
Returns:
A promise that resolves when the OCG visibility state has been set.
- Type
- Promise.<void>
Example
instance.setLayersVisibilityState({
visibleLayerIds: [1, 2, 3]
})
Sets the locale for the application. When setting a locale that doesn't exist it tries to
fall back to the parent locale when available. For example en-US
falls back to en
.
See PSPDFKit.I18n.locales to get a list of all the available locales.
Parameters:
Name | Type | Description |
---|---|---|
locale |
string | The locale to set the app to. It must be one of PSPDFKit.I18n.locales. |
Throws:
-
Will throw an error when the locale does not exist.
- Type
- PSPDFKit.Error
Returns:
void Returns a promise that resolves once the locale is set.
- Type
- Promise
Server only Set the maximum number of suggestions that will be shown when mentioning a user.
Parameters:
Name | Type | Description |
---|---|---|
maxMentionSuggestions |
number | The maximum number of suggestions that will be shown when mentioning a user. |
Example
instance.setMaxMentionSuggestions(5);
Set the precision value of all the newly created measurement annotations.
Parameters:
Name | Type | Description |
---|---|---|
precision |
PSPDFKit.MeasurementPrecision | Precision value |
Example
instance.setMeasurementPrecision(PSPDFKit.MeasurementPrecision.THREE);
Set the default value of scale for all newly created measurement annotations.
Parameters:
Name | Type | Description |
---|---|---|
scale |
PSPDFKit.MeasurementScale | Scale value |
Example
instance.setMeasurementScale(new PSPDFKit.MeasurementScale({
unitFrom: PSPDFKit.MeasurementScaleUnitFrom.CENTIMETERS,
unitTo: PSPDFKit.MeasurementScaleUnitTo.INCHES,
fromValue: 1,
toValue: 2,
}));
Allows the user to toggle the snapping behavior while creation of measurement annotations. The snapping points are the points are a combination of endpoints, midpoints and intersections.
Parameters:
Name | Type | Description |
---|---|---|
enabled |
boolean | Whether to enable/disable snapping behaviour for creation of measurement annotations. |
Server only
Set a list of users that can be mentioned in comments.
Parameters:
Name | Type | Description |
---|---|---|
mentionableUsers |
Array.<MentionableUser> | An array of PSPDFKit.MentionableUser objects. |
Example
instance.setMentionableUsers([
{ id: "1", name: "John Doe", displayName: "John", avatar: "https://example.com/avatar.png" },
{ id: "2", name: "Jane Doe", displayName: "Jane", avatar: "https://example.com/avatar.png" },
{ id: "3", name: "John Smith", displayName: "John", avatar: "https://example.com/avatar.png" },
]);
This method is used to update the setOnAnnotationResizeStart callback
When the supplied callback is invalid it will throw a PSPDFKit.Error that contains a detailed error message.
Parameters:
Name | Type | Description |
---|---|---|
setOnAnnotationResizeStartCallback |
PSPDFKit.AnnotationResizeStartCallback |
You can programmatically modify the properties of the comment just before it is created.
Parameters:
Name | Type | Description |
---|---|---|
callback |
PSPDFKit.OnCommentCreationStartCallback | The callback to set the values of created form fields programmatically. |
Returns:
- Type
- void
Example
instance.setOnCommentCreationStart((comment) => {
return comment.set('text', { format: 'xhtml', value: '<p>This comment has a default value</p>' });
});
You can programmatically modify the properties of the widget annotation and the associated form field just before it is created via the form creator UI.
Parameters:
Name | Type | Description |
---|---|---|
callback |
PSPDFKit.OnWidgetAnnotationCreationStartCallback | The callback to set the values of created form fields programmatically. |
Returns:
- Type
- void
Example
instance.setOnWidgetAnnotationCreationStart((annotation, formField) => {
return { annotation: annotation.set('opacity', 0.7) };
});
*** Standalone only ***
This method is used to set the tab order of annotations in a given page.
The tab order should be provided as an array of annotation IDs.
In the case of widget annotations associated to a radio form field, all the widgets
associated to the same form field will be rendered next to the first one found
in the provided Array
of annotation IDs.
Parameters:
Name | Type | Description |
---|---|---|
pageIndex |
number | |
annotationIdsSortCallback |
PSPDFKit.Instance~TabOrderUpdater | A callback that will get invoked with the annotations in the current tab order, and is expected to return the annotation IDs in the new tab order. |
Throws:
Examples
instance.setPageTabOrder(0, ["annotation-id-1", "annotation-id-2"]);
// 'radio-widget-id-2' will be rendered next to 'radio-widget-id-1', and navigated accordingly
instance.setPageTabOrder(0, ["radio-widget-id-1", "annotation-id-1", "annotation-id-2", "radio-widget-id-2"]);
This method is used to modify the current tab order of annotations.
Using this method, it is possible to specify the order in which annotations are navigated when using the keyboard.
The method accepts a page index as first argument, and a callback as second. This callback will be called with an array of annotations in the page sorted by their current tab order.
The callback should return an array of those annotations id
s following the new tab order.
Parameters:
Name | Type | Description |
---|---|---|
annotationIdsSortCallback |
PSPDFKit.Instance~TabOrderUpdater | A callback that will get invoked with the annotations in the current tab order, and is expected to return the annotation IDs in the new tab order. |
Throws:
-
Will throw an error when the supplied tab order is not valid.
- Type
- PSPDFKit.Error
Example
instance.setPageTabOrder(
1,
currentTabOrderedAnnotations => currentTabOrderedAnnotations
.sort((a, b) => a.boundingBox.left - b.boundingBox.left)
.map(annotation => annotation.id)
);
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
const state = instance.SearchState;
const newState = state.set("isLoading", true);
instance.setSearchState(newState);
Selects annotations in the user interface. If annotationOrAnnotationId
is empty, the
current selection will be cleared instead.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
annotationsOrAnnotationsIds |
PSPDFKi.Immutable.List.<(AnnotationsUnion|string)> |
<nullable> |
The annotations
model or annotations IDs you want to set as selected. If |
Standalone only
Adds LTV (Long Term Validation) information to an existing signature. See PSPDFKit.SignaturesInfo.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
certificates |
Array.<ArrayBuffer> | Array.<string> |
<nullable> |
Certificates used to sign the document. |
Returns:
Promise that resolves with a PSPDFKit.SignaturesInfo.
- Type
- Promise.<PSPDFKit.SignaturesInfo>
Example
instance.setSignaturesLTV(certificates)
.then(signaturesInfo => {
console.log(signaturesInfo.status)
if(signaturesInfo.signatures) {
const invalidSignatures = signaturesInfo.signatures
.filter(signature => !signature.ltv);
console.log(invalidSignatures);
}
});
Additional information can be found in
this guide article.
This method is used to update the stamp annotation templates.
It makes it possible to add new stamp and image annotation templates and edit or remove existing ones.
When you pass in an array
with PSPDFKit.Annotations.StampAnnotation, the current
templates will be immediately updated. Calling this method is also idempotent.
If you pass in a function, it will be immediately invoked and will receive the current
Array<PSPDFKit.Annotations.StampAnnotation | PSPDFKit.Annotations.ImageAnnotation> Array
as argument.
You can use this to modify the array based on its current value. This type of update is guaranteed
to be atomic - the value of currentStampAnnotationTemplates
can't change in between.
See: StampAnnotationTemplatesSetter
When one of the supplied PSPDFKit.Annotations.StampAnnotation or PSPDFKit.Annotations.ImageAnnotation is invalid, this method will throw a PSPDFKit.Error that contains a detailed error message.
Since stampAnnotationTemplates
is a regular JavaScript Array
, it can be manipulated
using standard Array
methods.
Parameters:
Name | Type | Description |
---|---|---|
stateOrFunction |
Array.<(PSPDFKit.Annotations.StampAnnotation|PSPDFKit.Annotations.ImageAnnotation)> | PSPDFKit.Instance~StampAnnotationTemplatesSetter | Either a new StampAnnotationTemplates |
Throws:
-
Will throw an error when the supplied stamp annotation template
array
is not valid. - Type
- PSPDFKit.Error
Examples
instance.setStampAnnotationTemplates(newStampAnnotationTemplates);
instance.stampAnnotationTemplates === newStampAnnotationTemplates; // => true
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 stored signatures list. It makes it possible to add new signatures and edit or remove existing ones.
Signatures are either ink or image annotations whose pageIndex
and boundingBox
is calculated at creation time.
When selected via UI such annotations are used as template to create new PSPDFKit.Annotations.InkAnnotations and PSPDFKit.Annotations.ImageAnnotations.
.
When you pass in a List of PSPDFKit.Annotations.InkAnnotation and PSPDFKit.Annotations.ImageAnnotation, the current list
of signatures will be immediately updated. Calling this method is also idempotent.
If you pass in a function, it will be invoked with the current List of PSPDFKit.Annotations.InkAnnotation and PSPDFKit.Annotations.ImageAnnotation
as argument.
You can use this to modify the list based on its current value.
This type of update is guaranteed to be atomic - the value of getStoredSignatures()
can't change in between.
See: StoredSignaturesSetter
When the application doesn't have signatures in store this method will invoke PSPDFKit.Configuration#populateStoredSignatures to retrieve the initial list of annotations and it will pass it to your function.
When the list is invalid, this method will throw an PSPDFKit.Error that contains a detailed error message.
Parameters:
Name | Type | Description |
---|---|---|
StoredSignaturesOrFunction |
Array.<PSPDFKit.ToolbarItem> | PSPDFKit.Instance~StoredSignaturesSetter | Either
a new |
Throws:
-
Will throw an error when the supplied items
array
is not valid. - Type
- PSPDFKit.Error
Examples
const signatures = fetch("/signatures")
.then(r => r.json())
.then(a => (
new PSPDFKit.Immutable.List(
a.map(PSPDFKit.Annotations.fromSerializableObject)
)
)
);
signatures.then(signatures => { instance.setStoredSignatures(signatures) });
instance.setStoredSignatures(signatures => signatures.reverse());
const signature = new PSPDFKit.Annotations.InkAnnotation({ lines: ..., boundingBox: ... });
instance.setStoredSignatures(signatures => signatures.push(signature));
instance.setStoredSignatures(signatures => signatures.shift());
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
const items = instance.toolbarItems;
items.reverse();
instance.setToolbarItems(newState);
instance.setToolbarItems(items => items.reverse());
instance.setToolbarItems(newItems);
instance.toolbarItems === newItems; // => true
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;
});
const myButton = {
type: "custom",
id: "my-button",
title: "Test Button",
icon: "https://example.com/icon.jpg",
disabled: true,
onPress() {
alert("test");
},
};
PSPDFKit.load({
toolbarItems: [...PSPDFKit.defaultToolbarItems, myButton],
// ...
}).then(instance => {
instance.setToolbarItems(items =>
items.map(item => {
if (item.id === "my-button") {
item.disabled = false;
}
return item;
})
);
});
This method is used to update the UI state of the PDF editor.
When you pass in a PSPDFKit.ViewState, the current state will be immediately overwritten. Calling this method is also idempotent.
If you pass in a function, it will be immediately invoked and will receive the current
PSPDFKit.ViewState as a property. You can use this to change state based on the
current value. This type of update is guaranteed to be atomic - the value of currentState
can't change in between.
See: ViewStateUpdater
Be aware that this behavior is different from a React component's setState
, because
it will not be deferred but initially applied. If you want to, you can always add deferring
behavior yourself. The approach we choose (immediate applying) makes it possible to control
exactly when the changes are flushed, which will allow fine control to work with other
frameworks (e.g. runloop-based frameworks like Ember).
Whenever this method is called (and actually changes the view state), the instance will trigger an PSPDFKit.Instance~ViewStateChangeEvent. However, if you use this method to change properties of the view state at once (e.g. zooming and currentPageIndex at the same time), the PSPDFKit.Instance~ViewStateChangeEvent will only be triggered once. The PSPDFKit.Instance~ViewStateChangeEvent will be triggered synchronously, that means that the code will be called before this function exits. This is true for both passing in the state directly and passing in an update function.
When the supplied PSPDFKit.ViewState is invalid, this method will throw an PSPDFKit.Error that contains a detailed error message.
Parameters:
Name | Type | Description |
---|---|---|
stateOrFunction |
PSPDFKit.ViewState | PSPDFKit.Instance~ViewStateUpdater | Either a new ViewState which would overwrite the existing one, or a callback that will get invoked with the current view state and is expected to return the new state. |
Throws:
-
Will throw an error when the supplied state is not valid.
- Type
- PSPDFKit.Error
Examples
const state = instance.viewState;
const newState = state.set("currentPageIndex", 2);
instance.setViewState(newState);
instance.setViewState(state => state.set("currentPageIndex", 2));
instance.setViewState(newState);
instance.viewState === newState; // => true
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)"
}
Digitally signs the document. On Standalone it can make sign the document with the certificates and private key provided by the user in PSPDFKit.SignaturePreparationData, or use the signing service optionally provided in the callback argument.
On Server, you can optionally specify additional data to be passed to the signing service.
Check the related guide article.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
signaturePreparationData |
PSPDFKit.SignaturePreparationData |
<nullable> |
Properties to prepare the signature with. |
twoStepSignatureCallbackOrSigningServiceData |
PSPDFKit.TwoStepSignatureCallback | PSPDFKit.SigningServiceData |
<nullable> |
Either a callback to be executed when the document is ready for signing (Standalone only) or optional data to be passed to the signing service. |
Returns:
Promise that resolves when the document is signed.
- Type
- Promise.<void>
Examples
instance.signDocument(null, function({ hash, fileContents }) {
return new Promise(function(resolve, reject) {
const PKCS7Container = getPKCS7Container(hash, fileContents);
if (PKCS7Container != null) {
return resolve(PKCS7Container)
}
reject(new Error("Could not retrieve the PKCS7 container."))
})
}).then(function() {
console.log("Document signed!");
})
instance.signDocument(null, { signingToken: "My security token" })
.then(function() {
console.log("Document signed!");
})
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
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 text lines of the given page.
- Type
- Promise.<PSPDFKit.Immutable.List.<PSPDFKit.TextLine>>
Enable actions like cut, copy, paste and duplicate for annotations using keyboard shortcuts Cmd/Ctrl+X
, Cmd/Ctrl+C
, Cmd/Ctrl+V
and Cmd/Ctrl+D
respectively.
Parameters:
Name | Type | Description |
---|---|---|
enabled |
boolean | Whether to enable/disable the clipboard actions. |
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.
Transforms a PSPDFKit page space bounding box to a raw PDF bounding rect.
A raw PDF bounding rect is an array of inset values: [left, bottom, right, top]
,
in PDF page space units (as opposted to PSPDFKit page units) where the top
and bottom
coordinates are actually relative to the distance to the bottom of the page.
Use this transform when you want to manage document entities with external tools.
Parameters:
Name | Type | Description |
---|---|---|
rect |
PSPDFKit.Geometry.Rect | The rectangle to be transformed |
pageIndex |
number | The index of the page you want to have information about. |
Throws:
-
Will throw an error when the supplied arguments is not valid.
- Type
- PSPDFKit.Error
Returns:
The resulting transformed rectangle as inset coordinates.
Transforms a raw PDF bounding rect from the PDF page space to PSPDFKit's page space.
Use this transform when you want to manage entities using their raw, original coordinates and dimensions according to the PDF spec (e.g. from a XFDF file).
Parameters:
Name | Type | Description |
---|---|---|
insetOrRawInset |
PSPDFKit.Geometry.Inset | Array.<number> | The inset to be transformed |
pageIndex |
number | The index of the page you want to have information about. |
Throws:
-
Will throw an error when the supplied arguments is not valid.
- Type
- PSPDFKit.Error
Returns:
The resulting transformed rectangle.
Updates object and changes its contents.
If you need to ensure that changes are persisted by the backend, please refer to: PSPDFKit.Instance#ensureChangesSaved.
New changes will be made visible in the UI instantly.
Parameters:
Name | Type | Description |
---|---|---|
changes |
PSPDFKit.Change | Array.<PSPDFKit.Change> | List.<PSPDFKit.Change> | A single change or list/array of changes that should be updated. |
Returns:
A promise that resolves to an array of changes or an error if some changes could not be updated.
- Type
- Promise.<Array.<PSPDFKit.Change>>
Example
const instance = await PSPDFKit.load(configuration);
// Get all annotations on the first page
const annotations = instance.getAnnotations(0);
// Grab the first one
const annotation = annotations.first();
const editedAnnotation = annotation.set("noPrint", true);
const updatedAnnotation = await instance.update(editedAnnotation);
editedAnnotation === updatedAnnotation; // => true
You can use this callback to set/modify the toolbar items present in the inline toolbar after the document has loaded.
The callback will receive the default items of the inline toolbar and the text that is currently selected {@linkPSPDFKit.TextSelection}
You can do the following modifications using this API:
- Add new items.
- Remove existing items.
- Change the order of the items.
- Customise each item eg change the
icon
of the a default toolbar item.
You can also use the hasDesktopLayout
flag provided to the callback to determine if the current UI is being rendered on
mobile or desktop. Based on that, you can implement different designs for Desktop and Mobile.
This callback gets called every time the inline toolbar is mounted.
Parameters:
Name | Type | Description |
---|---|---|
inlineTextSelectionToolbarItemsCallback |
PSPDFKit.InlineTextSelectionToolbarItemsCallback |
Example
instance.setInlineTextSelectionToolbarItems(({ defaultItems, hasDesktopLayout }, selection) => {
console.log(selection)
if (hasDesktopLayout) {
const node = document.createElement("div");
node.innerText = "Custom Item";
return [
...defaultItems,
{
type: "custom",
id: "custom-1",
node: node,
className: "Custom-Node",
onPress: () => alert("Custom node pressed!"),
},
{
type: "custom",
id: "custom-2",
title: "custom-button-2",
onPress: () => alert("Custom item pressed!"),
},
];
}
return defaultItems
});
Type Definitions
This event will be emitted whenever an annotation note icon is hovered, which by default shows the annotation note editor popover element.
The parameter is a PSPDFKit.AnnotationNotePressEvent.
Parameters:
Name | Type | Description |
---|---|---|
event |
PSPDFKit.AnnotationNoteHoverEvent |
Example
instance.addEventListener("annotationNote.hover", (event) => {
event.preventDefault();
});
This event will be emitted whenever an annotation note is selected by pressing its associated icon.
The parameter is a PSPDFKit.AnnotationNotePressEvent.
Parameters:
Name | Type | Description |
---|---|---|
event |
PSPDFKit.AnnotationNotePressEvent |
Example
instance.addEventListener("annotationNote.press", (event) => {
event.preventDefault();
});
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
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
instance.addEventListener("annotationPresets.update", (event) => {
event.preventDefault();
});
This event will fire whenever an annotation is being selected or unselected.
Parameters:
Name | Type | Description |
---|---|---|
annotations |
PSPDFKit.Immutable.List.<AnnotationsUnion> | The newly selected annotations, if any. |
Example
instance.addEventListener("annotationSelection.change", (annotations) => {
if (annotations.size !== 0) {
console.log("annotation is selected");
} else {
console.log("no annotation is selected");
}
});
This event will be emitted whenever an annotation loses focus.
The parameter is a PSPDFKit.AnnotationsBlurEvent.
Parameters:
Name | Type | Description |
---|---|---|
event |
PSPDFKit.AnnotationsBlurEvent |
Example
instance.addEventListener("annotations.blur", (event) => {
console.log(event.annotation, event.nativeEvent.type)
});
This event will be emitted whenever the current annotations change either due to a user action (eg. clicking the UI) or via PSPDFKit.Instance#create, PSPDFKit.Instance#update or PSPDFKit.Instance#delete.
The event might also be emitted every time the PSPDFKit's annotations model changes. This for example can happen when scrolling to a page and PSPDFKit loads the annotations for that page or when opening the annotations sidebar and PSPDFKit (has to) loads all the document annotations.
The change event will fire before all specific events and it could be used in case you want to perform some action regardless of which event caused the annotation to "change" (create, delete, update, load, internal load, etc). Consider using the specific events for more advanced use cases.
Example
instance.addEventListener("annotations.change", () => {
// ...
});
This event will be emitted whenever an annotation is copied using Cmd/Ctrl+C keyboard shortcut.
The parameter is a PSPDFKit.AnnotationsCopyEvent
Parameters:
Name | Type | Description |
---|---|---|
event |
PSPDFKit.AnnotationsCopyEvent |
Example
instance.addEventListener("annotations.copy", (event) => {
console.log(event.annotation)
});
This event will be emitted whenever new annotations were created (either via the public API or via the UI).
If PSPDFKit Instant is enabled, annotations created by remote clients will also cause this event to be emitted.
The parameter is a PSPDFKit.Immutable.List of created PSPDFKit.Annotations.
Parameters:
Name | Type | Description |
---|---|---|
createdAnnotations |
PSPDFKit.Immutable.List.<AnnotationsUnion> |
Example
instance.addEventListener("annotations.create", (createdAnnotations) => {
console.log(createdAnnotations);
});
This event will be emitted whenever an annotation is cut using Cmd/Ctrl+X keyboard shortcut.
The parameter is a PSPDFKit.AnnotationsCutEvent
Parameters:
Name | Type | Description |
---|---|---|
event |
PSPDFKit.AnnotationsCutEvent |
Example
instance.addEventListener("annotations.cut", (event) => {
console.log(event.annotation)
});
This event will be emitted whenever new annotations were deleted (either via the public API or via the UI).
The parameter is a PSPDFKit.Immutable.List of deleted PSPDFKit.Annotations.
Parameters:
Name | Type | Description |
---|---|---|
deletedAnnotations |
PSPDFKit.Immutable.List.<AnnotationsUnion> |
Example
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
instance.addEventListener("annotations.didSave", () => {
// ...
});
This event will be emitted whenever an annotation is duplicated using the Ctrl/Cmd+D keyboard shortcut.
The parameter is a PSPDFKit.AnnotationsDuplicateEvent
Parameters:
Name | Type | Description |
---|---|---|
event |
PSPDFKit.AnnotationsDuplicateEvent |
Example
instance.addEventListener("annotations.duplicate", (event) => {
console.log(event.annotation)
});
This event will be emitted whenever an annotation is focused.
The parameter is a PSPDFKit.AnnotationsFocusEvent.
Parameters:
Name | Type | Description |
---|---|---|
event |
PSPDFKit.AnnotationsFocusEvent |
Example
instance.addEventListener("annotations.focus", (event) => {
console.log(event.annotation, event.nativeEvent.type)
});
This event will be emitted whenever annotations are loaded from the annotation provider. This can happen more than once since we often load annotations on demand only.
The parameter is a PSPDFKit.Immutable.List of loaded PSPDFKit.Annotations.
Parameters:
Name | Type | Description |
---|---|---|
loadedAnnotations |
PSPDFKit.Immutable.List.<AnnotationsUnion> |
Example
instance.addEventListener("annotations.load", (loadedAnnotations) => {
console.log(loadedAnnotations);
});
This event will be emitted whenever an annotation is pasted using Cmd/Ctrl+V keyboard shortcut.
The parameter is a PSPDFKit.AnnotationsPasteEvent
Parameters:
Name | Type | Description |
---|---|---|
event |
PSPDFKit.AnnotationsPasteEvent |
Example
instance.addEventListener("annotations.paste", (event) => {
console.log(event.annotations)
});
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
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 an annotation is dragged or resized using the UI.
The parameter is a PSPDFKit.AnnotationsTransformEvent
Parameters:
Name | Type | Description |
---|---|---|
event |
PSPDFKit.AnnotationsTransformEvent |
Example
instance.addEventListener("annotations.transform", (event) => {
console.log(event.annotation.boundingBox)
});
This event will be emitted whenever new annotations were updated (either via the public API or via the UI).
The parameter is a PSPDFKit.Immutable.List of updated PSPDFKit.Annotations.
Parameters:
Name | Type | Description |
---|---|---|
updatedAnnotations |
PSPDFKit.Immutable.List.<AnnotationsUnion> |
Example
instance.addEventListener("annotations.update", (updatedAnnotations) => {
console.log(updatedAnnotations);
});
This event will be emitted when the user starts or ends an interaction with an annotation. See PSPDFKit.AnnotationsWillChangeReason for a comprehensive list of actions supported.
Note that this event is only emitted for actions performed through the UI.
Despite the name, it is not necessarily fired before each emission of PSPDFKit.Instance~AnnotationsChangeEvent, since that would not correspond to the list of possible reasons described in PSPDFKit.AnnotationsWillChangeReason on all cases.
Parameters:
Name | Type | Description |
---|---|---|
event |
PSPDFKit.AnnotationsWillChangeEvent |
Example
instance.addEventListener("annotations.willChange", event => {
const annotation = event.annotations.get(0);
if (event.reason === PSPDFKit.AnnotationsWillChangeReason.DELETE_START) {
console.log("Will open deletion confirmation dialog");
} else if (
event.reason === PSPDFKit.AnnotationsWillChangeReason.DELETE_END
) {
if (annotation) {
console.log("The user decided to delete the annotation.");
} else {
console.log("The user decided to not delete the annotation.");
}
}
});
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
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
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.Bookmark.
Parameters:
Name | Type | Description |
---|---|---|
createdBookmarks |
PSPDFKit.Immutable.List.<PSPDFKit.Bookmark> |
Example
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.Bookmark.
Parameters:
Name | Type | Description |
---|---|---|
deletedBookmarks |
PSPDFKit.Immutable.List.<PSPDFKit.Bookmark> |
Example
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
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.Bookmark.
Parameters:
Name | Type | Description |
---|---|---|
loadedBookmarks |
PSPDFKit.Immutable.List.<PSPDFKit.Bookmark> |
Example
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.Bookmark.
Parameters:
Name | Type | Description |
---|---|---|
updatedBookmarks |
PSPDFKit.Immutable.List.<PSPDFKit.Bookmark> |
Example
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
instance.addEventListener("bookmarks.willSave", () => {
// ...
});
This event will be emitted whenever the current comments change either via PSPDFKit.Instance#create, PSPDFKit.Instance#update or PSPDFKit.Instance#delete.
The change event will fire before all specific events. Consider using the specific events for more advanced use cases.
Example
instance.addEventListener("comments.change", () => {
// ...
});
This event will be emitted whenever new comments are created (either via the public API or via the UI).
The parameter is a PSPDFKit.Immutable.List of created PSPDFKit.Comment.
Parameters:
Name | Type | Description |
---|---|---|
createdComments |
PSPDFKit.Immutable.List.<PSPDFKit.Comment> |
Example
instance.addEventListener("comments.create", (createdComments) => {
console.log(createdComments);
});
This event will be emitted whenever comments are deleted (either via the public API or via the UI).
The parameter is a PSPDFKit.Immutable.List of deleted PSPDFKit.Comment.
Parameters:
Name | Type | Description |
---|---|---|
deletedComments |
PSPDFKit.Immutable.List.<PSPDFKit.Comment> |
Example
instance.addEventListener("comments.delete", (deletedComments) => {
console.log(deletedComments);
});
This event will be emitted whenever comments were saved to the comment provider.
This event will follow a PSPDFKit.Instance~CommentsWillSaveEvent.
Example
instance.addEventListener("comments.didSave", () => {
// ...
});
This event will be emitted whenever comments are loaded from the comment provider. This can happen more than once since we often load comments on demand only.
The parameter is a PSPDFKit.Immutable.List of loaded PSPDFKit.Comment.
Parameters:
Name | Type | Description |
---|---|---|
loadedComments |
PSPDFKit.Immutable.List.<PSPDFKit.Comment> |
Example
instance.addEventListener("comments.load", (loadedComments) => {
console.log(loadedComments);
});
This event will be emitted whenever comments are updated (either via the public API or via the UI).
The parameter is a PSPDFKit.Immutable.List of updated PSPDFKit.Comment.
Parameters:
Name | Type | Description |
---|---|---|
updatedComments |
PSPDFKit.Immutable.List.<PSPDFKit.Comment> |
Example
instance.addEventListener("comments.update", (updatedComments) => {
console.log(updatedComments);
});
This event will be emitted before comments will be saved to the comment provider.
Right now, this happens whenever attributes of the comment change (either via the public API or via the UI) and the comment is in a valid state.
You can use this to display a loading spinner for example. This event will always be followed by PSPDFKit.Instance~CommentsDidSaveEvent.
Example
instance.addEventListener("comments.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
instance.addEventListener("instant.connectedClients.change", (clients) => {
console.log(clients.toJS());
});
This event will be emitted whenever the CropArea begins being created, moved, or resized (via UI interaction).
Parameters:
Name | Type | Description |
---|---|---|
event |
PSPDFKit.CropAreaChangeStartEvent |
Example
instance.addEventListener("cropArea.changeStart", ({ area, pageIndex }) => {
console.log(area, pageIndex);
});
This event will be emitted whenever the crop area stops being created, moved or resized (via UI interaction).
Parameters:
Name | Type | Description |
---|---|---|
event |
PSPDFKit.CropAreaChangeStopEvent |
Example
instance.addEventListener("cropArea.changeStop", ({ area, pageIndex }) => {
console.log(area, pageIndex);
});
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
instance.addEventListener("document.change", (operations) => {
// ...
});
This event will be emitted whenever the document comparison UI is hidden.
Example
instance.addEventListener("documentComparisonUI.end", () => {
// ...
});
This event will be emitted whenever the document comparison UI is shown.
The event listener will receive the document comparison configuration object with which setDocumentComparisonMode() has been called.
Example
instance.addEventListener("documentComparisonUI.start", (documentComparisonConfiguration) => {
// ...
});
This callback can be used in the setDocumentEditorFooterItems() method to do atomic updates to the document editor footer items.
Parameters:
Name | Type | Description |
---|---|---|
currentDocumentEditorFooterItems |
Array.<PSPDFKit.DocumentEditorFooterItem> |
Returns:
The new document editor footer items.
- Type
- Array.<PSPDFKit.DocumentEditorFooterItem>
Example
instance.setDocumentEditorFooterItems(items => {
const button = instance.contentDocument.createElement('div');
button.innerText = "Custom Save"
items.push({
type: "custom",
node: button,
onPress(){
alert("save");
}
});
return items;
});
This callback can be used in the setDocumentEditorToolbarItems() method to do atomic updates to the document editor toolbar items.
Parameters:
Name | Type | Description |
---|---|---|
currentDocumentEditorToolbarItems |
Array.<PSPDFKit.DocumentEditorToolbarItem> |
Returns:
The new document editor toolbar items.
- Type
- Array.<PSPDFKit.DocumentEditorToolbarItem>
Example
instance.setDocumentEditorToolbarItems(items => {
const button = instance.contentDocument.createElement('div');
button.innerText = "Do something"
items.push({
type: "custom",
node: button,
onPress(){
alert("Do Something");
}
});
return items;
});
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
instance.addEventListener("formFieldValues.didSave", ({ response, error }) => {
// ...
});
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
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
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
instance.addEventListener("formFieldValues.willSave", () => {
// ...
});
This event will be emitted whenever the current form fields change either due to a user action (eg. clicking the UI) or via PSPDFKit.Instance#create, PSPDFKit.Instance#update or PSPDFKit.Instance#delete.
The change event will fire before all specific events and it could be used in case you want to perform some action regardless of which event caused the form fields to "change" (create, delete, update, load, internal load, etc). Consider using the specific events for more advanced use cases.
Example
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
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
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
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
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
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
instance.addEventListener("formFields.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
instance.addEventListener("forms.willSubmit", ({ preventDefault }) => {
// ...
});
This event will be emitted after calling PSPDFKit.Instance.history.undo or PSPDFKit.Instance.history.redo, or after pressing the main toolbar Undo or Redo buttons, optionally available.
If provided, the listener callback will receive a PSPDFKit.HistoryChangeEvent object.
Parameters:
Name | Type | Description |
---|---|---|
event |
PSPDFKit.HistoryChangeEvent |
Example
instance.addEventListener("history.change", (historyChangeEvent) => {
console.log(historyChangeEvent);
});
This event will be emitted after calling PSPDFKit.Instance.history.clear.
Example
instance.addEventListener("history.clear", () => {
console.log('History cleared.');
});
This event will be emitted after calling PSPDFKit.Instance.history.redo or after pressing the main toolbar Redo button, optionally available.
If provided, the listener callback will receive a PSPDFKit.HistoryChangeEvent object.
Parameters:
Name | Type | Description |
---|---|---|
event |
PSPDFKit.HistoryChangeEvent |
Example
instance.addEventListener("history.redo", (historyRedoEvent) => {
console.log(historyRedoEvent);
});
This event will be emitted after calling PSPDFKit.Instance.history.undo or after pressing the main toolbar Undo button, optionally available.
If provided, the listener callback will receive a PSPDFKit.HistoryChangeEvent object.
Parameters:
Name | Type | Description |
---|---|---|
event |
PSPDFKit.HistoryChangeEvent |
Example
instance.addEventListener("history.undo", (historyUndoEvent) => {
console.log(historyUndoEvent);
});
This event will be emitted before adding an annotation change to the actions history; if the
event's preventDefault()
method is called, the change will not be added and the action
will not be undoable.
If provided, the listener callback will receive a PSPDFKit.HistoryWillChangeEvent object.
Parameters:
Name | Type | Description |
---|---|---|
event |
PSPDFKit.HistoryWillChangeEvent |
Example
instance.addEventListener("history.willChange", (historyWillChangeEvent) => {
console.log(historyWillChangeEvent);
});
This event will fire whenever the list of ink signatures is changed (either a signature was added, updated, or deleted).
Example
instance.addEventListener("inkSignatures.change", () => {
console.log("ink signature list changed");
});
This event will fire whenever a signature is created and stored.
storedSignatures.create
payload returns null
values for the annotation
id
and name
. We return these values because the created signature is
not attached to the document hence it isn't assigned an id
or name
.
If you want to retrieve a complete list of values of the signature
annotation we suggest to listen to the annotations.create
event.
Parameters:
Name | Type | Description |
---|---|---|
annotation |
PSPDFKit.Annotations.InkAnnotation | PSPDFKit.Annotations.ImageAnnotation | The newly stored annotation. |
Example
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 | PSPDFKit.Annotations.ImageAnnotation | The deleted annotation. |
Example
instance.addEventListener("inkSignatures.delete", annotation => {
console.log(annotation);
});
This event will fire whenever one ink signature is updated.
Parameters:
Name | Type | Description |
---|---|---|
annotations |
PSPDFKit.Immutable.List.<(PSPDFKit.Annotations.InkAnnotation|PSPDFKit.Annotations.ImageAnnotation)> | The list of updated annotations. |
Example
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.).
This event internally uses the onpointerup
event triggered by the browser. This is an
implementation detail which we are documenting because it is useful to prevent the propagation of click events on custom overlay items.
Please don't rely on this behavior if possible and use it wisely as it might break in future.
The parameter is a PSPDFKit.PagePressEvent.
Parameters:
Name | Type | Description |
---|---|---|
event |
PSPDFKit.PagePressEvent |
Example
instance.addEventListener("page.press", (event) => {
console.log(event.point);
});
This event will be emitted whenever document save state changes. This reflects changes to return value of PSPDFKit.Instance.hasUnsavedChanges.
The parameter is SaveStateChangeEvent.
Parameters:
Name | Type | Description |
---|---|---|
event |
SaveStateChangeEvent |
Example
instance.addEventListener("document.saveStateChange", (event) => {
console.log(`Document has unsaved changes: ${event.hasUnsavedChanges}`);
});
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
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
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
instance.setStampAnnotationTemplates(stamps => {
stamps.pop(); // removes the last template of the stamps array
return stamps;
});
This event will fire whenever the list of ink signatures is changed (either a signature was added, updated, or deleted).
Example
instance.addEventListener("storedSignatures.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 | PSPDFKit.Annotations.ImageAnnotation | The newly stored annotation. |
Example
instance.addEventListener("storedSignatures.create", annotation => {
console.log(annotation);
});
This event will fire whenever a signature is deleted.
Parameters:
Name | Type | Description |
---|---|---|
annotation |
PSPDFKit.Annotations.InkAnnotation | PSPDFKit.Annotations.ImageAnnotation | The deleted annotation. |
Example
instance.addEventListener("storedSignatures.delete", annotation => {
console.log(annotation);
});
This event will fire whenever one ink signature is updated.
Parameters:
Name | Type | Description |
---|---|---|
annotations |
PSPDFKit.Immutable.List.<(PSPDFKit.Annotations.InkAnnotation|PSPDFKit.Annotations.ImageAnnotation)> | The list of updated annotations. |
Example
instance.addEventListener("storedSignatures.update", annotations => {
console.log(annotations);
});
This callback can be used in the setStoredSignatures() method to do atomic updates to the current list of signatures.
Parameters:
Name | Type | Description |
---|---|---|
currentStoredSignatures |
PSPDFKit.Immutable.List.<(PSPDFKit.Annotations.InkAnnotation|PSPDFKit.Annotations.ImageAnnotation)> |
Returns:
The new signatures list.
- Type
- PSPDFKit.Immutable.List.<(PSPDFKit.Annotations.InkAnnotation|PSPDFKit.Annotations.ImageAnnotation)>
Example
instance.setStoredSignatures(signatures => {
signatures.push(
new PSPDFKit.Annotations.InkAnnotation({
lines: ...,
boundingBox: ...,
})
);
return signatures;
});
This callback can be used in the setViewState() method to do atomic updates to the current view state.
Parameters:
Name | Type | Description |
---|---|---|
tabOrderedAnnotations |
Array.<PSPDFKit.AnnotationsUnion> | Annotations ordered by the current tab order. |
Returns:
Annotations IDs ordered following the new tab order.
- Type
- Array.<string>
Example
// Sort page 0 annotations by their top position
instance.setPageTabOrder(
0,
currentTabOrderedAnnotations => currentTabOrderedAnnotations
.sort((a, b) => a.boundingBox.top - b.boundingBox.top)
.map(annotation => annotation.id)
);
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
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
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
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 PSPDFKit.ViewState as first argument, and the previous PSPDFKit.ViewState
as second.
Parameters:
Name | Type | Description |
---|---|---|
viewState |
PSPDFKit.ViewState | The new view state |
previousViewState |
PSPDFKit.ViewState | The previous view state |
Examples
instance.addEventListener("viewState.change", (viewState, previousViewState) => {
console.log(previousViewState.toJS());
console.log(viewState.toJS());
});
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
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
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
instance.addEventListener("viewState.zoom.change", (zoom) => {
console.log(zoom);
});