Hierarchy
Indexable
- [key: string]: any
Properties
{ … }
The History API includes methods to undo and redo annotation operations: creation, updates and deletions may be reverted and restored by means of this API.
The implementation does not fully revert an annotation to its previous state:
- The
updatedAtfield will have changed to the current time. - If an annotation deletion is undone, the restored annotation will have a different
idthan the original. - If an annotation deletion is undone, the restored annotation will appear at the front, regardless of its original stacking position.
- Annotation changes that only affect the
updatedAtproperty are not tracked, and the updated annotation is considered identical to the previous one in this case. - Newly created empty text annotations are not recorded in the history. This ensures that accidental creation of such annotations, followed by pressing escape or clicking outside, will not persist in the undo and redo history.
The feature only accounts for annotations modified locally, whether using the API or the toolbar Undo and Redo buttons. If an annotation is modified externally, by another Instant client, for example, undoing will not revert the annotation state to the one just before the external change, but to the previous to that one: external annotation operations are not undone, but overridden.
Annotation operations performed while the History API is disabled can also be considered external for that effect. This is also the case for annotation operations that result from Instant Comments changes, like deleting the last comment of a comment thread, which results on the comment marker being deleted, and which cannot therefore be undone.
However, comment markers directly deleted with the API may be restored with its former comments.
Annotation presets are not restored by undo and redo operations.
| Property | Description |
|---|---|
| canRedo | Returns |
| canUndo | Returns |
| clear | Removes all undoable and redoable operations available. |
| disable | Disables the History API: attempting to undo or redo previous operations with the API or the UI will not be possible, but the previous undoable and redoable operations will be preserved, and available if the History API is enabled again with NutrientViewer.Instance#history.enable. |
| enable | Enables the History API, making undoing and redoing possible. If there were previous undoable or redoable operations, they will be now available. |
| redo | When called, the last undone annotation operation will be performed again. Note that if an annotation deletion has been undone, and then redone by calling this function, it will reappear in front of any other annotations, even if that was not its original stacking order. Returns |
| undo | When called, the last local annotation operation will be reverted. The outcome will vary depending on the type of that operation:
Note that if a deleted annotation is restored by calling this function, it will reappear in front of any other annotations, even if that was not its original stacking order. Returns |
Accessors
- get annotationCreatorName(): string | null
The current annotation creator name. This is set using
instance.setAnnotationCreatorName().Returns
string | null
Returns a deep copy of the latest annotation presets. This value changes whenever the user interacts with NutrientViewer or whenever Instance.setAnnotationPresets is called.
Mutating this object will have no effect.
Returns
{ [key: string]: AnnotationPreset }
NOTE This method is only available with Nutrient 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 "instant.connectedClients.change" event 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).
Returns
An NutrientViewer.Immutable.Map of the connected clients.
Example
Find out how many total clients are currently connected
instance.connectedClients.count();Find out how many distinct users are currently connected
instance.connectedClients.groupBy(c => c.userId).count();Find out how many anonymous clients are currently connected
instance.connectedClients.filter(c => !c.userId).count();
Access the shadow root object of the Nutrient Web SDK's 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
documentobject of the Nutrient Web SDK's viewer frame instead.Returns
Example
instance.contentDocument.addEventListener("mouseup", handleMouseUp);
Headless content editor control. The same methods the bundled UI uses internally are exposed here so that a custom toolbar can read the current state of the live session and drive an active UI session programmatically.
Session save/discard/dirty-flag/export and starting a programmatic session live on
Instancedirectly: saveContentEditingSession, discardContentEditingSession, hasUnsavedContentEditingChanges, exportContentEditorPDF, beginContentEditingSession.Subscribe to "contentEditor.stateChange" to re-render a custom toolbar in response to state changes.
Returns
Access the
windowobject of the Nutrient Web SDK's viewer frame. This can be used to quickly interact with elements (using our public CSS API) inside the viewer.Returns
Example
instance.contentWindow.location;
- get currentAnnotationPreset(): string | null | undefined
Get the current active annotation preset ID
Returns
string | null | undefined
- get currentZoomLevel(): number
- get disablePointSnapping(): boolean
Whether to disable snapping to points when creating annotations for measurement tools
Returns
booleanExample
instance.setViewState(viewState => viewState.set('disablePointSnapping', true))
Returns a deep copy of the latest document editor toolbar items. This value changes whenever the user interacts with NutrientViewer or whenever Instance#setDocumentEditorToolbarItems is called.
Mutating this array will have no effect.
Returns
- get editableAnnotationTypes(): NutrientViewer.Immutable.Set<
new (...args: any[]) => AnnotationsUnion,
>Returns a deep copy of the latest editableAnnotationTypes. This value changes whenever Instance.setEditableAnnotationTypes is called.
Mutating this object will have no effect.
Returns
NutrientViewer.Immutable.Set<new (...args: any[]) => AnnotationsUnion>
- get locale(): string
Returns the current locale for the application.
Returns
stringThe current locale for the application.
- get maximumZoomLevel(): number
The maximum zoom level. This value depends on the current viewport and page dimensions. Defaults to
10but can be bigger so that theFIT_TO_WIDTHandFIT_TO_VIEWPORTZoomModes always fit.Returns
number
- get minimumZoomLevel(): number
The minimum zoom level. This value depends on the current viewport and page dimensions. Defaults to
0.5but can be bigger so that theFIT_TO_WIDTHandFIT_TO_VIEWPORTZoomModes always fit.Returns
number
Returns the latest search state. This value changes whenever the user interacts with NutrientViewer or whenever Instance#setSearchState is called.
The search state can be used to finely control the current search UI.
Returns
- get stampAnnotationTemplates(): (
| NutrientViewer.Annotations.StampAnnotation
| NutrientViewer.Annotations.ImageAnnotation
)[]Returns a deep copy of the latest stamp and image annotation templates. This value changes whenever NutrientViewer.Instance#setStampAnnotationTemplates is called.
Mutating this array will have no effect.
Returns
Returns a deep copy of the latest toolbar items. This value changes whenever the user interacts with NutrientViewer or whenever Instance#setToolbarItems is called.
Mutating this array will have no effect.
Returns
- get totalPageCount(): number
The total number of pages in the current document.
Returns
numberExample
// Log the total number of pages
console.log(instance.totalPageCount);
Returns the latest view state. This value changes whenever the user interacts with NutrientViewer or whenever Instance#setViewState is called.
When you want to keep a reference to the latest view state, you should always listen on the "viewState.change" to update your reference.
Returns
- get zoomStep(): number
Returns
number
Methods
Aborts the current print job.
Returns
voidErrors
This method will throw when printing is disabled or no printing is currently being processed.
- addEventListener<K extends keyof EventNameToHandlerMap>(
action: K,
listener: EventNameToHandlerMap[K],
): voidRegisters an event listener for a specific event type.
Use this method to listen for changes and actions within the viewer, such as annotation updates, page navigation, form field changes, and more. Each supported event type is associated with a specific handler signature, ensuring type safety and clarity.
A list of all supported events can be found in NutrientViewer.EventName.
Usage Notes
- The
actionparameter must be one of the supported event names listed above. - The
listenerparameter must match the corresponding event listener type for the event. - You can register multiple listeners for the same event.
- To remove a listener, use Instance#removeEventListener with the same function reference.
- The event system is modeled after the DOM API: removing a listener requires the exact same function reference as was used for registration.
If you attempt to register a listener for an unsupported event, a NutrientViewer.Error will be thrown.
Type Parameters
Kextends keyof EventNameToHandlerMapThe event name to listen for. Must be a key of Events.EventNameToHandlerMap.
Parameters
actionKThe event name to listen for. See the table above for supported values.
listenerEventNameToHandlerMap[K]The function to be called when the event is emitted.
Returns
voidExample
Registering a listener for a view state change
instance.addEventListener("viewState.change", (viewState) => {
console.log(viewState.toJS());
});Handling an unknown event (throws an error)
try {
instance.addEventListener("doesnotexist", () => {});
} catch (error) {
(error instanceof NutrientViewer.Error); // => true
}Errors
If the supplied event name is not valid.
- The
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
operationsDocumentOperationsUnion[]Operations to be performed on the document.
Returns
Promise<unknown>Promise that resolves with an array of results.
Example
Apply 90 degrees rotation to page 0
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<void>Promise that resolves when the redactions has been applied.
Example
// Applies redactions
instance.applyRedactions().then(function() {
console.log("The document has been redacted.");
});
Creates and returns a new content editing session.
If called in a Server-backed instance, we will download the document and WASM in the background automatically.
Using this method requires a license that includes the Content Editor component.
Returns
A promise that resolves to a ContentEditing.Session object.
Errors
If a session (either UI or API) is already in progress.
- calculateFittingTextAnnotationBoundingBox(
annotation: NutrientViewer.Annotations.TextAnnotation,
): NutrientViewer.Annotations.TextAnnotationTakes a NutrientViewer.Annotations.TextAnnotation and returns a new NutrientViewer.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
annotationNutrientViewer.Annotations.TextAnnotationThe text annotation that needs its bounding box adjusted.
Returns
The text annotation that has it's bounding box adjusted.
Example
textAnnotation = instance.calculateFittingTextAnnotationBoundingBox(textAnnotation);
Closes the annotation note panel by clearing the active annotation note.
Returns
void
- compareDocuments(
comparisonDocuments: ComparisonDocuments,
operation: NutrientViewer.ComparisonOperation,
): Promise<DocumentComparisonResult | AIDocumentComparisonResult>Compares documents based on the operation provided. It supports both standard text comparison and AI-powered analysis and tagging.
Parameters
comparisonDocumentsComparisonDocumentsDescriptors of the original and changed documents.
operationNutrientViewer.ComparisonOperationThe comparison operation to be applied (either standard text or AI).
Returns
A promise that resolves to the result of the comparison. The type depends on the operation:
DocumentComparisonResultfor text comparison,AIDocumentComparisonResultfor AI operations.Example
Compare two documents
const operation = new NutrientViewer.ComparisonOperation("text", { numberOfContextWords: 2 });
const originalDocument = new NutrientViewer.DocumentDescriptor({ filePath: "path/to/original.pdf", pageIndexes: [0]});
const changedDocument = new NutrientViewer.DocumentDescriptor({ filePath: "path/to/changed.pdf", pageIndexes: [0]});
const comparisonDocuments = { originalDocument, changedDocument };
instance.compareDocuments(operation, comparisonDocuments)
.then((comparisonResults) => {
console.log(comparisonResults);
});AI-powered analysis
const aiOperation = new NutrientViewer.ComparisonOperation(
NutrientViewer.ComparisonOperationType.AI,
{ operationType: NutrientViewer.AIComparisonOperationType.ANALYZE }
);
instance.compareDocuments(comparisonDocuments, aiOperation)
.then((result) => {
// For AI operations, check the result type
if (NutrientViewer.isAIDocumentComparisonResult(result)) {
console.log('AI Summary:', result.summary);
console.log('Categories:', result.categories);
}
});AI-powered tagging with categories
const tagOperation = new NutrientViewer.ComparisonOperation(
NutrientViewer.ComparisonOperationType.AI,
{
operationType: NutrientViewer.AIComparisonOperationType.TAG,
categories: ["Legal", "Financial"]
}
);
instance.compareDocuments(comparisonDocuments, tagOperation)
.then((result) => {
// For AI operations, check the result type
if (NutrientViewer.isAIDocumentComparisonResult(result)) {
console.log('Tagged References:', result.references);
// result.changes contains the original DocumentComparisonResult
}
});
copySelectedAnnotations(): NutrientViewer.Immutable.List<
NutrientViewer.Annotations.Annotation<{ … }>,
>Copies all currently selected annotations into the internal clipboard and emits an
annotations.copyevent.Returns
An immutable List of the copied annotations.
Errors
If no annotation is selected.
Creates new changes. Changes include annotations, bookmarks, form fields, and comments. If a change does not provide an
id, this method assigns one. Caller-provided IDs are preserved and validated for uniqueness, which is useful when another change needs to refer to the new object before creation. If you need to ensure that changes are persisted by the backend, please refer to: NutrientViewer.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.
When creating the first comment in a thread, create both the root annotation and the NutrientViewer.Comment in the same call. The comment's
rootIdmust match the root annotation'sid.Parameters
Returns
Example
NutrientViewer.load(configuration).then(function(instance) {
const annotation = new NutrientViewer.Annotations.InkAnnotation({
pageIndex: 0,
lines: NutrientViewer.Immutable.List([
NutrientViewer.Immutable.List([
new NutrientViewer.Geometry.DrawingPoint({ x: 0, y: 0 }),
new NutrientViewer.Geometry.DrawingPoint({ x: 100, y: 100}),
])
])
});
instance.create(annotation).then(function(createdAnnotations) {
console.log(createdAnnotations);
});
})Create a comment thread.
NutrientViewer.load(configuration).then(async (instance) => {
const rootId = NutrientViewer.generateInstantId();
const marker = new NutrientViewer.Annotations.CommentMarkerAnnotation({
id: rootId,
pageIndex: 0,
boundingBox: new NutrientViewer.Geometry.Rect({
top: 50,
left: 50,
width: 20,
height: 20,
}),
});
const comment = new NutrientViewer.Comment({
pageIndex: 0,
rootId,
text: {
format: "plain",
value: "Please review this area.",
},
});
const createdChanges = await instance.create([marker, comment]);
await instance.ensureChangesSaved(createdChanges);
});
Creates a new attachment and returns a Promise that resolves to the created attachments ID.
Parameters
blobBlobThe attachment data as a Blob object.
Returns
Promise<string>A promise that resolves to the attachment ID.
Example
NutrientViewer.load(configuration).then(function(instance) {
instance.createAttachment(blob).then(function(attachmentId) {
console.log(attachmentId);
});
})Errors
Will throw an error when the file can not be read.
- createLayer(
options: { name: string },
): Promise<{ name: string; ocgId: number; radioGroup?: number }>*** Standalone only ***
Creates a new OCG layer in the document.
The created layer can be used as a target for DocumentOperations.FlattenAnnotationsOperation to flatten annotations into a togglable layer rather than directly into page content.
Parameters
options{ name: string }Options for the new layer.
name: string
The name of the layer.
Returns
Promise<{ name: string; ocgId: number; radioGroup?: number }>A promise that resolves to the created OCG layer.
Example
const layer = await instance.createLayer({ name: 'User A Annotations' });
console.log(layer); // => { name: 'User A Annotations', ocgId: 42 }
createRedactionsBySearch(
term: string,
options?: { … },
): Promise<NutrientViewer.Immutable.List<string>>Searches in the PDF document and creates a redaction annotation for each search result. You can search for a text, regex or use one of the patterns we provide. See NutrientViewer.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 NutrientViewer.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
termstringThe text, regex or pattern you want to search for.
options{ … }
OptionalSearch options object.
- OptionalannotationPreset?: RedactionAnnotationPreset
Redaction annotation preset.
- OptionalcaseSensitive?: boolean
Whether the search will be case-sensitive or not. Default is
falseifsearchTypeisNutrientViewer.SearchType.TEXTorNutrientViewer.SearchType.WORD_BASED, andtruefor other types of searches. - OptionalpageRange?: number
Starting from the
startpage, the number of pages to search. Default is to the end of the document. - OptionalsearchInAnnotations?: boolean
Set to
falseif you don't want to search in annotations.Default Value
true - OptionalsearchType?: "text" | "preset" | "regex" | "word_based"
Redactions Search Type.
Default Value
NutrientViewer.SearchType.TEXT - OptionalstartPageIndex?: number
The page number to start the search from.
Default Value
0
Returns
Promise<NutrientViewer.Immutable.List<string>>Promise that resolves when the redaction annotations have been created. Returns a list of new Redaction Annotation IDs.
Example
// Search and add redactions
instance.createRedactionsBySearch(NutrientViewer.SearchPattern.CREDIT_CARD_NUMBER, {
searchType: NutrientViewer.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} = NutrientViewer.Annotations
instance.addEventListener("annotations.create", annotations => {
const redactions = annotations.filter(annot => annot instanceof RedactionAnnotation)
if (redactions.size > 0) {
console.log("Redactions: ", redactions.toJS())
}
});
cutSelectedAnnotations(): Promise<
NutrientViewer.Immutable.List<
NutrientViewer.Annotations.Annotation<{ … }>,
>,
>Cuts all currently selected annotations. Stores them in the internal clipboard with a
'cut'action marker, deletes them from the document, and emits anannotations.cutevent.The clipboard and event are only updated after the delete succeeds. If the delete fails, the clipboard is left unchanged.
Returns
Promise<
NutrientViewer.Immutable.List<
NutrientViewer.Annotations.Annotation<{ … }>
>
>An immutable List of the cut annotations.
Errors
If no annotation is selected or if any selected annotation cannot be deleted (e.g. due to collaboration permissions).
- delete(
changeIds:
| string
| Change
| (string | Change)[]
| NutrientViewer.Immutable.List<(string | Change)>,
): Promise<Change[]>Deletes a change. This can be called with a change ID.
If you need to ensure that changes are persisted by the backend, please refer to: Instance#ensureChangesSaved.
Deleted changes will be made visible in the UI instantly.
This can delete comments as well as annotations. Deleting the root annotation of a comment thread deletes the associated comments in that thread.
If the deleted change is a
NutrientViewer.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 associatedNutrientViewer.FormFieldonly includes that annotation in itsannotationIdslist, the form field will also be deleted.If there are more widget annotations remaining in the
annotationIdslist, as could be the case for radio buttons, for example, the form field'sannotationIdsproperty will be updated by removing the deleted annotation'sidfrom it.Parameters
changeIdsstring
| Change
| (string | Change)[]
| NutrientViewer.Immutable.List<(string | Change)>A single id or a list/array of ids of changes that should be deleted.
Returns
Example
NutrientViewer.load(configuration).then(function(instance) {
instance.delete(1).then(function() {
console.log("Object with ID 1 deleted.");
});
});Delete a comment.
const instance = await NutrientViewer.load(configuration);
const comments = await instance.getComments();
const comment = comments.first();
if (comment?.id) {
await instance.delete(comment.id);
}
If there are any annotations groups, this function will return all annotations groups. deleteAnnotationsGroup
Parameters
annotationGroupIdstring | null | undefinedThe annotation group id.
Returns
void
Discards changes made in the current UI content editing session and exits content editing mode.
This is the programmatic equivalent of pressing the "Don’t Save" button in the exit content editor dialog.
Using this method requires a license that includes the Content Editor component.
Returns
Promise<void>A promise that resolves when the session has been discarded.
Errors
If the Content Editor license feature is not available.
If no UI content editing session is currently active.
If the session is currently being saved.
duplicateSelectedAnnotations(): NutrientViewer.Immutable.List<
NutrientViewer.Annotations.Annotation<{ … }>,
>Duplicates all currently selected annotations in place. Unlike copy+paste, this does not use the internal clipboard.
Returns
An immutable List of the original (source) annotations.
Errors
If no annotation is selected.
- ensureChangesSaved(
changes: Change | Change[] | NutrientViewer.Immutable.List<Change>,
): Promise<Change[]>Ensures that changes have been saved to the backend and returns the current persisted state of these changes.
This method returns a promise that will resolve to an array of Change.
Parameters
Returns
Example
NutrientViewer.load(configuration).then(function(instance) {
instance.create(newAnnotation)
.then(instance.ensureChangesSaved)
.then(function() {
console.log('Annotation persisted by annotation provider');
});
});
@public
executeAction(
action: NutrientViewer.Actions.Action,
options?: { … },
): Promise<void>Executes a PDF action.
This can be used with action objects obtained from APIs such as NutrientViewer.Instance#getDocumentOutline and NutrientViewer.Instance#getBookmarks, or with manually created action objects.
In server-backed mode, JavaScript actions require a supported execution context. Use the
contextoption to pass the triggering annotation or form field.Execution is fail-fast: the action tree traversal stops at the first error and the returned promise is rejected. Any side effects from actions already executed before the error are not rolled back.
Parameters
actionNutrientViewer.Actions.ActionThe action to execute.
options= {}{ … }
Optional action execution settings.
- Optionalcontext?:
| { type: "none" }
| { annotation: NutrientViewer.Annotations.Annotation; type: "annotation" }
| {
annotation?:
| NutrientViewer.Annotations.Annotation<
{
action: NutrientViewer.Actions.Action
| null;
additionalActions:
| {
onPageClose?: NutrientViewer.Actions.Action;
onPageHidden?: NutrientViewer.Actions.Action;
onPageOpen?: NutrientViewer.Actions.Action;
onPageVisible?: NutrientViewer.Actions.Action;
onPointerDown?: NutrientViewer.Actions.Action;
onPointerEnter?: NutrientViewer.Actions.Action;
onPointerLeave?: NutrientViewer.Actions.Action;
onPointerUp?: NutrientViewer.Actions.Action;
}
| null;
APStreamCache: { cache: string }
| { attach: string }
| undefined;
blendMode:
| "normal"
| "multiply"
| "screen"
| "overlay"
| "darken"
| "lighten"
| "colorDodge"
| "colorBurn"
| "hardLight"
| "softLight"
| "difference"
| "exclusion";
boundingBox: NutrientViewer.Geometry.Rect
| null;
canReply: boolean | undefined;
canSetGroup: boolean | undefined;
createdAt: Date | null;
createdBy: string | null;
creatorName: string | null;
customData: Record<string, unknown> | null;
enrichment: AnnotationEnrichmentJSON | null | undefined;
group: string | null | undefined;
hidden: boolean | null;
id: string | null;
isAnonymous: boolean;
isCommentThreadRoot: boolean;
isDeletable: boolean | undefined;
isEditable: boolean | undefined;
locked: boolean | null;
lockedContents: boolean | null;
name: string | null;
noPrint: boolean | null;
noRotate: boolean;
note: string | null;
noView: boolean | null;
noZoom: boolean;
opacity: number | null;
pageIndex: number | null;
pdfObjectId: number | null;
readOnly: boolean | null;
rotation: number;
subject: string | null;
updatedAt: Date | null;
[key: string]: unknown;
},
>
| null;
formFieldName: string;
type: "formField";
}Sender context for action execution.
Default Value
{ type: "none" } - OptionaltriggerEventType?: ActionTriggerEventType | WidgetActionTriggerEventType
Trigger event context used when executing NutrientViewer.Actions.JavaScriptAction.
Default Value
"onPointerDown"
Returns
Promise<void>Example
Execute an outline element action
const outline = await instance.getDocumentOutline();
const firstItem = outline.first();
if (firstItem?.action) {
await instance.executeAction(firstItem.action);
}Execute a custom action
await instance.executeAction(new NutrientViewer.Actions.GoToAction({ pageIndex: 5 }));Execute a JavaScript action with annotation context
await instance.executeAction(linkAnnotation.action, {
context: {
type: "annotation",
annotation: linkAnnotation
},
triggerEventType: "onPointerDown"
});Errors
Throws when the action is invalid or execution fails.
Exports the PDF with pending content editor changes applied, without ending the session.
Requires a UI content editing session to be in progress (see the Content Editing guide).
Returns
A promise that resolves with the exported PDF as an ArrayBuffer.
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 Configuration#instantJSON to load it.
annotationswill follow the Instant Annotation JSON format specification.formFieldValueswill follow the Instant Form Field Value JSON format specification.Optionally a
versionargument 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
versionnumberOptionalOptional Instant JSON version for annotations.
Returns
Instant JSON as a plain JavaScript 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();
});
@public
Exports the document converted to the specified output format as an
ArrayBuffer. This can be used to download the resulting file.An
optionsobject should be passed to the method with aformatproperty set to one of the supported conversion output formats: OfficeDocumentFormat.Parameters
optionsExportOfficeFlagsExport options object.
Returns
The binary contents of the PDF.
Example
Download as DOCX
instance.exportOffice({ format: NutrientViewer.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.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
flattenandincrementalboth set totrueat 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
flagsExportPDFFlags = {}Export options object.
Returns
The binary contents of the PDF.
Example
Export the PDF content
instance.exportPDF().then(function (buffer) {
buffer; // => ArrayBuffer
});Export the PDF with password and permissions
instance.exportPDF({
permissions: {
userPassword: "123",
ownerPassword: "123",
documentPermissions: [NutrientViewer.DocumentPermissions.annotationsAndForms]
}
}).then(function (buffer) {
buffer; // => ArrayBuffer
});Download the PDF by using an
<a>taginstance.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
ArrayBufferthat can be used to download the PDF.Parameters
operationsDocumentOperationsUnion[]Operations to be performed on the document.
Returns
Promise that resolves with the binary contents of the modified PDF.
Example
Export the modified PDF content
const operations = [
{
type: "rotatePages",
pageIndexes: [0],
rotateBy: 90
}
];
instance.exportPDFWithOperations(operations).then(function (buffer) {
buffer; // => ArrayBuffer
});Download the modified PDF by using an
<a>tagconst 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 Configuration#XFDF to load it.
For Server-Backed setups, only saved annotations will be exported.
Parameters
ignorePageRotationboolean = falseOptional 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 Configuration#XFDFIgnorePageRotation the annotations will be imported in the same orientation no matter the page rotation.
Returns
Promise<string>XFDF as a plain text.
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 NutrientViewer.Immutable.List of NutrientViewer.Annotations.Annotation 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
- NutrientViewer.EventName.ANNOTATIONS_CHANGE,
- NutrientViewer.EventName.ANNOTATIONS_WILL_SAVE, or
- NutrientViewer.EventName.ANNOTATIONS_DID_SAVE 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
pageIndexnumberThe page index for the annotations you want.
pageIndexis zero-based and has a maximum value oftotalPageCount - 1Returns
Resolves to annotations for the given page.
Example
instance.getAnnotations(0).then(function (annotations) {
annotations.forEach(annotation => {
console.log(annotation.pageIndex);
});
// Filter annotations by type
annotations.filter(annotation => {
return annotation instanceof NutrientViewer.Annotations.InkAnnotation;
})
// Filter annotations at a specific point
const pointInFirstPage = new NutrientViewer.Geometry.Point({ x: 20, y: 30 });
const annotationsAtPointInPage = annotationsOnFirstPage.filter(annotation => {
return annotation.boundingBox.isPointInside(pointInFirstPage);
});
// Get the number of currently loaded annotations
const totalAnnotations = annotations.size;
})
- getAnnotationsGroups(): | NutrientViewer.Immutable.Map<
string,
{ annotationsIds: NutrientViewer.Immutable.Set<string>; groupKey: string },
>
| nullThis function will return all annotations groups, if there are any annotations groups.
Returns
NutrientViewer.Immutable.Map<
string,
{ annotationsIds: NutrientViewer.Immutable.Set<string>; groupKey: string }
>
| nullAnnotations groups
Fetches an attachment or an embedded file based on its ID.
Parameters
attachmentIdstringThe ID of the attachments or embedded files that should be fetched.
Example
NutrientViewer.load(configuration).then(function(instance) {
instance.getAttachment("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad").then(function(image) {
console.log(image);
});
})Errors
Will throw an error when the file can not be read.
Returns a NutrientViewer.Immutable.List of 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 NutrientViewer.EventName.BOOKMARKS_CHANGE, NutrientViewer.EventName.BOOKMARKS_WILL_SAVE, or NutrientViewer.EventName.BOOKMARKS_DID_SAVE to update your reference.
Returns
Resolves to bookmarks for the given page.
Example
instance.getBookmarks().then(function (bookmarks) {
bookmarks.forEach(bookmark => {
console.log(bookmark.name);
});
// Get the number of currently loaded bookmarks
const totalBookmarks = bookmarks.size;
})
- getComments(
options?: { includeDrafts?: boolean },
): Promise<NutrientViewer.Immutable.List<NutrientViewer.Comment>>Returns a NutrientViewer.Immutable.List of 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 NutrientViewer.EventName.COMMENTS_CHANGE.
Parameters
options{ includeDrafts?: boolean } = DEFAULT_GET_COMMENTS_OPTIONSAn object to configure the comments retrieval - GetCommentsOptions
- OptionalincludeDrafts?: boolean
Whether to include draft comments in the returned list.
Default Value
false
Returns
Resolves to comments.
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 NutrientViewer.Immutable.List of NutrientViewer.OutlineElement
- getDocumentPermissions(): Promise<
Record<
| "printHighQuality"
| "extract"
| "annotationsAndForms"
| "assemble"
| "extractAccessibility"
| "fillForms"
| "modification"
| "printing",
boolean,
>,
>Returns the current DocumentPermissions of the document.
Returns
Promise<
Record<
| "printHighQuality"
| "extract"
| "annotationsAndForms"
| "assemble"
| "extractAccessibility"
| "fillForms"
| "modification"
| "printing",
boolean
>
>A Promise resolving to an object containing the document permissions keys along with their status (
trueorfalse).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 NutrientViewer.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.
Example
const embeddedFilesInfo = await instance.getEmbeddedFiles();
Returns a NutrientViewer.Immutable.List of all NutrientViewer.FormFields for this document.
Returns
Resolves to a list of all form fields.
Example
instance.getFormFields().then(formFields => {
formFields.forEach(formField => {
console.log(formField.name);
});
// Filter form fields by type
formFields.filter(formField => (
formField instanceof NutrientViewer.FormFields.TextFormField
));
// Get the total number of form fields
const totalFormFields = formFields.size;
})
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, orArray.<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
Record<string, null | string | string[]>A simplified object that contains all form field values.
Example
await instance.getFormFields()
const formFieldValues = instance.getFormFieldValues();
console.log(formFieldValues); // => { textField: 'Text Value', checkBoxField: ['A', 'B'], buttonField: null }
getInkSignatures
- getInkSignatures(): Promise<
NutrientViewer.Immutable.List<
| NutrientViewer.Annotations.InkAnnotation
| NutrientViewer.Annotations.ImageAnnotation,
>,
>DeprecatedReturns a copy of the available stored signatures. Signatures are ink and image annotations and therefore can be converted to JavaScript objects with NutrientViewer.Annotations.toSerializableObject.
When the application doesn't have signatures in store this method will invoke Configuration#populateStoredSignatures to retrieve the initial list of annotations.
Returns
Promise<
NutrientViewer.Immutable.List<
| NutrientViewer.Annotations.InkAnnotation
| NutrientViewer.Annotations.ImageAnnotation
>
>Promise that resolves with an Immutable list of signatures
Example
Retrieve the signatures and convert them to JSON
instance
.getInkSignatures()
.then(signatures => signatures.map(NutrientViewer.Annotations.toSerializableObject).toJS());
*** Standalone only ***
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
visibleLayerIdsArraythat contains the list of layers identified by theirocgIdnumber, which are currently visible.Returns
Promise<OCGLayersVisibilityState>A promise that resolves to the OCG layers visibility state.
Example
instance.getLayersVisibilityState().then(function (layersVisibilityState) {
console.log(layersVisibilityState); // => { visibleLayerIds: [1, 2, 3] }
});
Extracts the text behind a NutrientViewer.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
annotationTextMarkupAnnotationsUnionThe text markup annotation you want to extract the text behind.
Returns
Promise<string>The text behind the annotation.
Example
Get the text of all text markup annotations on the first page:
const annotations = await instance.getAnnotations(0);
const markupAnnotations = annotations.filter(
annotation => annotation instanceof NutrientViewer.Annotations.MarkupAnnotation
);
const text = await Promise.all(
markupAnnotations.map(instance.getMarkupAnnotationText)
);
console.log(text);
- getOverlappingAnnotations(
annotationOrFormField:
| AnnotationsUnion
| NutrientViewer.FormFields.FormField,
): Promise<NutrientViewer.Immutable.List<AnnotationsUnion>>Returns a NutrientViewer.Immutable.List of NutrientViewer.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
annotationOrFormFieldAnnotationsUnion | NutrientViewer.FormFields.FormFieldThe 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.
Example
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 NutrientViewer.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 NutrientViewer.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.
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
Arrayof annotation IDs.The returned order reflects the tab order defined in the document. Annotations that are not currently rendered or focusable in the viewer (for example hidden annotations, or form widgets when forms are disabled) may still be included, matching Standalone behavior.
In Server mode this requires a Document Engine version that exposes the annotation tab order; with older versions the returned promise rejects.
Parameters
pageIndexnumberReturns
Promise<string[]>A promise that resolves to an ordered array of annotation IDs.
Example
Get the tab order of annotations in page 0
instance.getPageTabOrder(0);Errors
Will throw an error when the supplied page index is not a number.
If multiple annotations are selected, this function will return the set of selected annotations.
Returns
NutrientViewer.Immutable.List<AnnotationsUnion> | null
Gets the digital signatures validation information for all the signatures present in the current document. See DigitalSignatures.SignaturesInfo.
Requires both the
Digital SignaturesandForm Viewing and Fillinglicense features. WithoutForm Viewing and Filling, signature form fields are not recognized in the document and this method resolves with an emptysignaturesarray — even on a signed document — and the signature validation status banner will not be shown.Additional information can be found in this guide article.
Returns
Promise that resolves with a DigitalSignatures.SignaturesInfo.
Example
Retrieve signatures information
instance.getSignaturesInfo()
.then(signaturesInfo => {
console.log(signaturesInfo.status)
if(signaturesInfo.signatures) {
const invalidSignatures = signaturesInfo.signatures
.filter(signature => signature.signatureValidationStatus !== NutrientViewer.SignatureValidationStatus.valid);
console.log(invalidSignatures);
}
});
- getStoredSignatures(): Promise<
NutrientViewer.Immutable.List<
| NutrientViewer.Annotations.InkAnnotation
| NutrientViewer.Annotations.ImageAnnotation,
>,
>Returns a copy of the available stored signatures. Signatures are ink and image annotations and therefore can be converted to JavaScript objects with NutrientViewer.Annotations.toSerializableObject.
When the application doesn't have signatures in store this method will invoke Configuration#populateStoredSignatures to retrieve the initial list of annotations.
Returns
Promise<
NutrientViewer.Immutable.List<
| NutrientViewer.Annotations.InkAnnotation
| NutrientViewer.Annotations.ImageAnnotation
>
>Promise that resolves with an Immutable list of signatures
Example
Retrieve the signatures and convert them to JSON
instance
.getStoredSignatures()
.then(signatures => signatures.map(NutrientViewer.Annotations.toSerializableObject).toJS());
- getTextFromRects(
pageIndex: number,
rects: NutrientViewer.Immutable.List<NutrientViewer.Geometry.Rect>,
): Promise<string>Given a list of rects and their page index, extracts the text intersecting them. This can be useful to get the text that overlaps a focused annotation to give more context to screen reader users.
Warning: The computed text might be partial as we just look behind the absolute coordinates of a rect to see what text it is intersecting.
Parameters
pageIndexnumberThe page index where the rects are located
An immutable list of rects
Returns
Promise<string>The text that intersect the rects.
Example
Get the text of all ink annotations on the first page:
const annotations = await instance.getAnnotations(0);
const inkAnnotationsRects = annotations.filter(
annotation => annotation instanceof NutrientViewer.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
NutrientViewer.TextSelection | nullA promise that resolves to the current text selection, or
nullif no text is selected.Example
Get the text selection as a string
const currentSelection = instance.getTextSelection();
if (currentSelection != null) {
const text = await currentSelection.getText();
alert(`Selection: '${text}'`);
}
groupAnnotations(
annotationsOrAnnotationsId?: NutrientViewer.Immutable.List<
string
| NutrientViewer.Annotations.Annotation<{ … }>,
>,
): voidGroup annotations in the user interface.
Parameters
annotationsOrAnnotationsIdNutrientViewer.Immutable.List<
string
| NutrientViewer.Annotations.Annotation<{ … }>
>OptionalThe 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
void
Returns
trueif any local changes are not yet saved. This can be used in combination with Configuration.autoSaveMode to implement fine grained save controls.Whenever changes are saved (for example, when calling NutrientViewer.Instance#save), the method will return
falseagain.Returns
booleanWhether unsaved changes are present or not.
Example
NutrientViewer.load(configuration).then(function(instance) {
instance.hasUnsavedChanges(); // => false
});
Returns whether the current UI content editing session has unsaved changes.
Returns
falseif no UI content editing session is active.Returns
booleantrueif there are unsaved changes,falseotherwise.
Forces the annotation rendering order to be recalculated on all visible pages.
Re-sorting happens automatically whenever annotations change in the SDK's state — for example, after NutrientViewer.Instance#update. You only need to call this when your comparator depends on inputs the SDK cannot observe (external application state, or annotation properties such as
customDatathat you mutated without going through the regular update path).Returns
voidExample
const annotation = annotations.get(0).set("customData", { zIndex: 10 });
await instance.update(annotation);
instance.invalidateAnnotationRenderingOrder();
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
pageIndexnumberThe index of the page you want to have information about. If none is provided, the first page (pageIndex
0) will be used.The rect in PDF page coordinates that you want to jump to.
Returns
voidExample
Jump and zoom to the ink annotation
instance.jumpAndZoomToRect(inkAnnotation.pageIndex, inkAnnotation.boundingBox);Errors
Will throw an error when the supplied arguments are not valid.
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
pageIndexnumberThe index of the page you want to have information about. If none is provided, the first page (pageIndex
0) will be used.The rect in PDF page coordinates that you want to jump to.
Returns
voidExample
Jump to the ink annotation
instance.jumpToRect(inkAnnotation.pageIndex, inkAnnotation.boundingBox);Errors
Will throw an error when the supplied arguments is not valid.
openAnnotationNote(
annotationOrAnnotationId?:
| string
| NutrientViewer.Annotations.Annotation<{ … }>
| null,
): NutrientViewer.Annotations.Annotation<{ … }>Selects the given annotation and opens its note panel. Resolves the annotation from an ID, instance, or the current selection.
Parameters
The annotation, its ID, or
null/undefinedto use the current selection.Returns
NutrientViewer.Annotations.Annotation<{ … }>
The resolved annotation.
Errors
If the annotation cannot be found.
If a text annotation is currently in
EDITINGmode.
Returns the PageInfo for the specified page index. If there is no page at the given index, returns
null.Parameters
pageIndexnumberThe index of the page you want to have information about
Returns
NutrientViewer.PageInfo | nullThe PageInfo or
null.Example
// Get information about the first page
const info = instance.pageInfoForIndex(0);
if (info) {
console.log(info.width, info.height);
}
@public
Pastes annotations from the internal clipboard into the document. If the clipboard contains annotations from a
'cut'operation, the clipboard is cleared after pasting (one-time paste). Copied annotations can be pasted repeatedly.Returns
numberThe number of annotations pasted.
Errors
If the clipboard is empty.
- print(
options?:
| "DOM"
| "EXPORT_PDF"
| { excludeAnnotations?: boolean; mode?: "DOM"
| "EXPORT_PDF" },
): voidPrint the document programmatically.
Parameters
options"DOM"
| "EXPORT_PDF"
| { excludeAnnotations?: boolean; mode?: "DOM"
| "EXPORT_PDF" }OptionalPrint options object.
- "DOM"
- "EXPORT_PDF"
- { excludeAnnotations?: boolean; mode?: "DOM" | "EXPORT_PDF" }
- OptionalexcludeAnnotations?: boolean
Whether to exclude annotations from the printout.
Default Value
false - Optionalmode?: "DOM" | "EXPORT_PDF"
Optional print mode. See NutrientViewer.PrintMode
Returns
voidErrors
This method will throw when printing is disabled, currently in process or when an invalid NutrientViewer.PrintMode was supplied.
This method is used to remove an existing CustomOverlayItem.
Parameters
idstringThe
idof the item to remove.Returns
voidExample
Create and then remove a text node.
const id = "1";
const item = new NutrientViewer.CustomOverlayItem({
id: id,
node: document.createTextNode("Hello from Nutrient Web SDK."),
pageIndex: 0,
position: new NutrientViewer.Geometry.Point({ x: 100, y: 200 }),
});
instance.setCustomOverlayItem(item);
instance.removeCustomOverlayItem(id);
- removeEventListener<K extends keyof EventNameToHandlerMap>(
action: K,
listener: EventNameToHandlerMap[K],
): voidThis method can be used to remove an event listener registered via 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).
Type Parameters
Kextends keyof EventNameToHandlerMapParameters
actionKThe action you want to add an event listener to. See the list on Instance#addEventListener for possible event types.
listenerEventNameToHandlerMap[K]A listener function.
Returns
voidExample
Proper approach - Use the same reference for registering and removing
const callback = someFunction.bind(this)
instance.addEventListener("viewState.zoom.change", callback);
instance.removeEventListener("viewState.zoom.change", callback);Wrong approach - Creates two different functions
instance.addEventListener("viewState.zoom.change", someFunction.bind(this));
// This will not work because `Function#bind()` will create a new function!
instance.removeEventListener("viewState.zoom.change", someFunction.bind(this));Errors
Will throw an error when the supplied event is not valid.
renderPageAsArrayBuffer
- renderPageAsArrayBuffer(
dimension: { width: number } | { height: number },
pageIndex: number,
): Promise<ArrayBuffer>StandaloneProvided a
dimensionandpageIndexrenders a page of a document and returns the result asArrayBuffer. This can be used as thumbnail.You can specify a width or height (but not both at the same time) as the first
dimensionargument, 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 of400px. We set the width of the<canvas>tag to200px, so the image will be sharp on high DPI screens.Parameters
dimension{ width: number } | { height: number }The size of the resulting image. Only accepts either
widthorheight, but not both. The other dimension will be calculated accordingly.- { width: number }
width: number
The width of the resulting image.
- { height: number }
height: number
The height of the resulting image.
pageIndexnumberThe index of the page you want to have information about.
Returns
The raw image as bitmap.
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);
}); - { width: number }
- renderPageAsImageURL(
dimension: { width: number } | { height: number },
pageIndex: number,
): Promise<string>Generates a URL to an image for the first page of a document or the page of the provided
pageIndex. This can be used as thumbnail.You can specify a width or height (but not both at the same time) as the first
dimensionargument, 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
srcfor animgtag. The following example will load the cover of the loaded document with a width of400px.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
dimension{ width: number } | { height: number }The size of the resulting image. Only accepts either
widthorheight, but not both. The other dimension will be calculated accordingly.- { width: number }
width: number
The width of the resulting image.
- { height: number }
height: number
The height of the resulting image.
pageIndexnumberThe index of the page you want to have information about.
Returns
Promise<string>The image url.
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);
}
} - { width: number }
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.
Returns
void
With NutrientViewer.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 NutrientViewer.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<void>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 NutrientViewer.SaveError.
Example
NutrientViewer.load(configuration).then(async (instance) => {
const annotation = new NutrientViewer.Annotations.InkAnnotation({
pageIndex: 0,
lines: NutrientViewer.Immutable.List([
NutrientViewer.Immutable.List([
new NutrientViewer.Geometry.DrawingPoint({ x: 0, y: 0 }),
new NutrientViewer.Geometry.DrawingPoint({ x: 100, y: 100}),
])
])
});
await instance.create(annotation);
await instance.save(); // Now the annotation gets saved.
})
Saves changes made in the current UI content editing session and exits content editing mode.
This is the programmatic equivalent of pressing the "Save" button in the exit content editor dialog.
Using this method requires a license that includes the Content Editor component.
Returns
Promise<void>A promise that resolves when the save is complete.
Errors
If the Content Editor license feature is not available.
If no UI content editing session is currently active.
If the session is currently being saved.
search(
term: string,
options?: { … },
): Promise<NutrientViewer.Immutable.List<NutrientViewer.SearchResult>>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 SearchState.minSearchQueryLength.
Shorter queries will throw an error.
Parameters
termstringThe search term.
options= {}{ … }
Parameters used for search operation.
- OptionalcaseSensitive?: boolean
Whether the search will be case-sensitive or not. Default is
falseifsearchTypeisNutrientViewer.SearchType.TEXTorNutrientViewer.SearchType.WORD_BASED, andtruefor other types of searches. - OptionalendPageIndex?: number
The last page index to search (inclusive).
options.startPageIndexmust be provided if this parameter is given. - OptionalsearchInAnnotations?: boolean
Whether you want to search in annotations.
Default Value
false - OptionalsearchType?: "text" | "preset" | "regex" | "word_based"
The search type which describes whether the query is a text, pattern or regex.
Default Value
NutrientViewer.SearchType.TEXT - OptionalstartPageIndex?: number
The page index to start searching from.
options.endPageIndexmust be provided if this parameter is given.
Returns
Resolves to an immutable list of search results.
Example
Search for all occurrences of
fooinstance.search("foo").then(results => {
console.log(results.size);
});Search within a page range.
instance.search("foo", { startPageIndex: 1, endPageIndex: 4 }).then(results => {
console.log(results.size);
});Search for a regex.
instance.search("Q[a-z]+ck\\sC.*[tT]", { searchType: NutrientViewer.SearchType.REGEX }).then(results => {
console.log(results.size);
});Search for all date patterns on the pages.
instance.search(NutrientViewer.SearchPattern.DATE, { searchType: NutrientViewer.SearchType.PATTERN }).then(results => {
console.log(results.size);
});Search for a regex in a case-insensitive way.
instance.search("he[a-z]+", { searchType: NutrientViewer.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
annotationCreatorNamestring | nullOptionalReturns
void
- setAnnotationPresets(
stateOrFunction:
| Record<string, AnnotationPreset>
| AnnotationPresetCallback,
): voidThis 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
objectwith keyed 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 annotation presets 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
currentAnnotationPresetscan't change in between. See: AnnotationPresetCallbackWhen one of the supplied AnnotationPreset is invalid, this method will throw an Error that contains a detailed error message.
Since
annotationPresetsis a regular JavaScriptobject, it can be manipulated using standardObjectmethods.Parameters
stateOrFunctionRecord<string, AnnotationPreset> | AnnotationPresetCallbackEither a new AnnotationPresets
objectwhich would overwrite the existing one, or a callback that will get invoked with the current annotation presets and is expected to return the new annotation presetsobject.Returns
voidExample
The new changes will be applied immediately
instance.setAnnotationPresets(newAnnotationPresets);
instance.annotationPresets === newAnnotationPresets; // => trueAdding an annotation preset for an ellipse annotation variant.
const myAnnotationPreset = {
dashedEllipse: {
strokeDashArray: [3, 3],
}
}
instance.setAnnotationPresets(annotationPresets => ({ ...annotationPresets, myAnnotationPreset }))Errors
Will throw an error when the supplied annotation preset
objectis not valid.
- setAnnotationRenderingOrderComparator(
comparator: AnnotationRenderingOrderComparator | null,
): voidSets a custom comparator that controls the visual rendering order of non-interactive annotations on each page. When set, this comparator replaces the SDK's default type-based rendering order for annotations such as text markups, ink, images, shapes, and stamps.
Interactive annotations — widget annotations (form fields), link annotations, and signature annotations — are always rendered above all other annotations regardless of the comparator. This is required to preserve keyboard tab order and accessibility.
The comparator receives two annotations and must return
-1if the first annotation should render below (behind) the second, or1if it should render above (in front of) the second. A strict total order is required.Pass
nullto clear the comparator and revert to the default rendering order.Limitations:
- Widget, link, and signature annotations always render on top, independent of this comparator, to preserve keyboard accessibility.
- It does not change the keyboard tab order. Use NutrientViewer.Instance#setPageTabOrder to customize that separately.
- Hit testing (click/tap) follows the visual stacking produced by this comparator: the topmost rendered annotation receives pointer events first.
- It does not affect annotation order in exported PDFs or backend storage. The ordering is purely a local, view-layer concern.
Parameters
comparatorAnnotationRenderingOrderComparator | nullA comparator function, or
nullto revert to the default rendering order.Returns
voidExample
Render image annotations behind everything else:
instance.setAnnotationRenderingOrderComparator((a, b) => {
const isImageA = a instanceof NutrientViewer.Annotations.ImageAnnotation;
const isImageB = b instanceof NutrientViewer.Annotations.ImageAnnotation;
if (isImageA !== isImageB) return isImageA ? -1 : 1;
if (a.createdAt < b.createdAt) return -1;
if (a.createdAt > b.createdAt) return 1;
return a.id < b.id ? -1 : 1;
});Use customData to store and control z-index:
instance.setAnnotationRenderingOrderComparator((a, b) => {
const zA = a.customData?.zIndex ?? 0;
const zB = b.customData?.zIndex ?? 0;
if (zA !== zB) return zA < zB ? -1 : 1;
if (a.createdAt < b.createdAt) return -1;
if (a.createdAt > b.createdAt) return 1;
return a.id < b.id ? -1 : 1;
});Clear the custom comparator and revert to default:
instance.setAnnotationRenderingOrderComparator(null);
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
hasDesktopLayoutto 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
annotationToolbarItemsCallbackAnnotationToolbarItemsCallbackReturns
voidExample
Add a new annotation toolbar item
instance.setAnnotationToolbarItems((annotation, { defaultAnnotationToolbarItems, hasDesktopLayout }) => {
const node = document.createElement('node')
node.innerText = "Custom Item"
const icon = `<svg xmlns="http://www.w3.org/2000/svg" height="24" width="24" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4" /></svg>`
return [{
id: "custom",
type: "custom",
node: node,
icon: icon,
className: 'Custom-Node',
onPress: () => alert("Custom item pressed!")
}, ...defaultAnnotationToolbarItems];
});
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
nullas argument.When the supplied key does not correspond with an existing AnnotationPreset, this method will throw an Error that contains a detailed error message.
Parameters
annotationPresetIDstring | nullOptionalAnnotation preset name.
Returns
voidExample
The new changes will be applied immediately
instance.setCurrentAnnotationPreset("ink");
instance.currentAnnotationPreset === "ink"; // => trueSetting an annotation preset for a closed arrow line annotation.
instance.setAnnotationPresets(annotationPresets => {
return {
...annotationPresets,
line: {
...annotationPresets.line,
lineCaps: {
end: "closedArrow"
}
}
}
});
instance.setCurrentAnnotationPreset("line");
instance.setViewState(viewState =>
viewState.set("interactionMode", NutrientViewer.InteractionMode.SHAPE_LINE),
);Errors
Will throw an error when the supplied annotation preset key does not exist.
This method is used to set a new CustomOverlayItem or update an existing one.
Parameters
The item to create or update.
Returns
voidExample
Add a text node to the first page.
let item = new NutrientViewer.CustomOverlayItem({
id: "1",
node: document.createTextNode("Hello from Nutrient Web SDK."),
pageIndex: 0,
position: new NutrientViewer.Geometry.Point({ x: 100, y: 200 }),
});
instance.setCustomOverlayItem(item);Update a text node.
item = item.set("node", document.createTextNode("Hello again my friend!!!"));
instance.setCustomOverlayItem(item);
Sets the current custom renderers. When this function is called with a new CustomRenderers object, all visible custom rendered annotations are immediately updated.
Parameters
customRenderersCustomRenderersReturns
void
setCustomUIConfiguration(
customUIConfigurationOrCustomUIConfigurationSetter:
| (
(
customUI: Partial<Record<"Sidebar", Partial<{ … }>>> | null,
) => CustomUI
)
| Partial<Record<"Sidebar", Partial<{ … }>>>,
): voidSets the current custom UI configuration. When this function is called with a new CustomUI object, all visible sidebars are immediately updated.
- setDocumentComparisonMode(
documentComparisonConfiguration: DocumentComparisonConfiguration | null,
): Promise<void>Standalone only
Enables or disables the document comparison UI.
When a DocumentComparisonConfiguration object is passed, the document comparison UI is mounted and initialized with the provided settings. The returned promise resolves once the mode change has been applied, while the comparison UI is being shown and before it has finished rendering, so it does not indicate that comparison has completed. The comparison UI does not expose a completion signal.
When
nullis passed, the document comparison UI is hidden if it was being shown, and the returned promise settles once comparison teardown finishes: it resolves after the mode change has been applied, and the UI is removed on the render that follows. If the document comparison UI was not being shown, the promise resolves immediately without making any changes. If comparison teardown fails, the promise rejects and the comparison UI stays mounted.Parameters
documentComparisonConfigurationDocumentComparisonConfiguration | nullInitial document comparison configuration.
Returns
Promise<void>Promise that resolves once the requested comparison mode change has been applied.
Example
Initialize and show the document comparison UI
instance.setDocumentComparisonMode({
documentA: {
source: fetch("old-document.pdf").then(res => res.arrayBuffer())
},
documentB: {
source: fetch("new-document.pdf").then(res => res.arrayBuffer())
},
autoCompare: true
});
- setDocumentEditorToolbarItems(
documentEditorToolbarItemsOrFunction:
| DocumentEditorToolbarItem[]
| (
(
currentState: DocumentEditorToolbarItem[],
) => DocumentEditorToolbarItem[]
),
): voidThis 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
arrayof 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
arrayof 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 ofcurrentDocumentEditorToolbarItemscan't change in between. See: DocumentEditorToolbarItemsSetterWhen one of the supplied DocumentEditorToolbarItem is invalid, this method will throw an Error that contains a detailed error message.
Since
itemsis a regular JavaScriptArrayof object literals it can be manipulated using standard array methods likeforEach,map,reduce,spliceand so on. Additionally you can use any 3rd party library for array manipulation like lodash or just.Parameters
documentEditorToolbarItemsOrFunctionDocumentEditorToolbarItem[]
| (
(
currentState: DocumentEditorToolbarItem[]
) => DocumentEditorToolbarItem[]
)Either a new
arrayof DocumentEditorToolbarItem which would overwrite the existing one, or a callback that will get invoked with the current toolbar items and is expected to return the newarrayof items.Returns
voidExample
Use ES2015 arrow functions and the update callback to reduce boilerplate
instance.setDocumentEditorToolbarItems(items => items.reverse());The new changes will be applied immediately
instance.setDocumentEditorToolbarItems(newItems);
instance.documentEditorToolbarItems === newItems; // => trueChanging a property of a custom button
const myButton = {
type: "custom",
id: "my-button",
onPress() {
alert("test");
},
};Errors
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.
setDocumentOutline
- setDocumentOutline(
outline: NutrientViewer.Immutable.List<NutrientViewer.OutlineElement>,
): Promise<void>StandaloneSets the document outline (table of content).
Parameters
The outline to set.
Returns
Promise<void>A promise that resolves when the outline has been set.
- setEditableAnnotationTypes(
editableAnnotationTypes: (new (...args: any[]) => AnnotationsUnion)[],
): voidThis method is used to update the editable annotation types.
When one of the supplied NutrientViewer.Annotations.Annotation is invalid, this method will throw an Error that contains a detailed error message.
Parameters
editableAnnotationTypes(new (...args: any[]) => AnnotationsUnion)[]Returns
voidExample
// Only allow editing ink annotations
instance.setEditableAnnotationTypes([NutrientViewer.Annotations.InkAnnotation]);
instance.editableAnnotationTypes === [NutrientViewer.Annotations.InkAnnotation]; // => trueErrors
Will throw an error when the supplied array is not valid.
- setEditingAnnotation(
annotationOrAnnotationId?: string | AnnotationsUnion | null,
autoSelectText?: boolean | null,
): voidSelects an annotation in the user interface and enters edit mode. If
annotationOrAnnotationIdis empty, the current selection will be cleared instead.This method works with NutrientViewer.Annotations.TextAnnotation and NutrientViewer.Annotations.NoteAnnotation. When called with other annotation types that don't have any text it will simply select the annotation.
Parameters
The annotation model or annotation ID you want to set as selected. If
nullis used, the current selection will be cleared instead.autoSelectTextboolean | nullOptionalWhether the text should be automatically selected.
Returns
void
Updates the values of form fields. It's possible to update multiple form fields at once.
The object must use the NutrientViewer.FormFields.FormField#name as a key and the values must be of type
null,string, orArray.<string>. Anullvalue will reset the form field to eithernull, 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
formFieldValuesRecord<string, null | string | string[]>An object that contains the form field names that should be updated as keys and their value as values.
Returns
Promise<void>Resolves when the values have been set.
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
groupstringThe new group that you want to use for all the newly created form-fields, comments and annotations.
Returns
void
setInkSignatures
- setInkSignatures(
stateOrFunction:
| NutrientViewer.Immutable.List<
| NutrientViewer.Annotations.InkAnnotation
| NutrientViewer.Annotations.ImageAnnotation,
>
| (
(
annotations: NutrientViewer.Immutable.List<
| NutrientViewer.Annotations.InkAnnotation
| NutrientViewer.Annotations.ImageAnnotation,
>,
) => NutrientViewer.Immutable.List<
| NutrientViewer.Annotations.InkAnnotation
| NutrientViewer.Annotations.ImageAnnotation,
>
),
): Promise<void>DeprecatedThis 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
pageIndexandboundingBoxis calculated at creation time. When selected via UI such annotations are used as template to create new NutrientViewer.Annotations.InkAnnotations and NutrientViewer.Annotations.ImageAnnotations.When you pass in a List of NutrientViewer.Annotations.InkAnnotation and NutrientViewer.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 NutrientViewer.Annotations.InkAnnotation and NutrientViewer.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.When the application doesn't have signatures in store this method will invoke 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 Error that contains a detailed error message.
Parameters
stateOrFunctionNutrientViewer.Immutable.List<
| NutrientViewer.Annotations.InkAnnotation
| NutrientViewer.Annotations.ImageAnnotation
>
| (
(
annotations: NutrientViewer.Immutable.List<
| NutrientViewer.Annotations.InkAnnotation
| NutrientViewer.Annotations.ImageAnnotation
>
) => NutrientViewer.Immutable.List<
| NutrientViewer.Annotations.InkAnnotation
| NutrientViewer.Annotations.ImageAnnotation
>
)a new
arrayof signatures which would overwrite the existing one, or a callback that will get invoked with the current toolbar items and is expected to return the newarrayof items.Returns
Promise<void>Example
Fetch and set a list of signatures
const signatures = fetch("/signatures")
.then(r => r.json())
.then(a => (
new NutrientViewer.Immutable.List(
a.map(NutrientViewer.Annotations.fromSerializableObject)
)
)
);
signatures.then(signatures => { instance.setInkSignatures(signatures) });Use ES2015 arrow functions and the update callback to reduce boilerplate
instance.setInkSignatures(signatures => signatures.reverse());Add a Ink Signature to the existing list
const signature = new NutrientViewer.Annotations.InkAnnotation({
pageIndex: 0,
lines: NutrientViewer.Immutable.List([NutrientViewer.Immutable.List([new NutrientViewer.Geometry.DrawingPoint({ x: 0, y: 0 })])]),
boundingBox: new NutrientViewer.Geometry.Rect({ left: 0, top: 0, width: 100, height: 100 })
});
instance.setInkSignatures(signatures => signatures.push(signature));Remove the first Ink Signature from the list
instance.setInkSignatures(signatures => signatures.shift());Errors
Will throw an error when the supplied items
arrayis not valid.
- setInlineTextSelectionToolbarItems(
inlineTextSelectionToolbarItemsCallback: InlineTextSelectionToolbarItemsCallback,
): voidYou 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 NutrientViewer.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
iconof the a default toolbar item.
You can also use the
hasDesktopLayoutflag 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
inlineTextSelectionToolbarItemsCallbackInlineTextSelectionToolbarItemsCallbackThe callback to set the inline text selection toolbar items.
Returns
voidExample
Add a custom button and a custom node to the toolbar.
instance.setInlineTextSelectionToolbarItems(({ defaultItems, hasDesktopLayout }, selection) => {
console.log(selection)
if (hasDesktopLayout) {
const node = document.createElement("div");
node.innerText = "Custom Item";
return [
...defaultItems,
{
type: "custom",
id: "custom-1",
node: node,
className: "Custom-Node",
onPress: () => alert("Custom node pressed!"),
},
{
type: "custom",
id: "custom-2",
title: "custom-button-2",
onPress: () => alert("Custom item pressed!"),
},
];
}
return defaultItems
});
This method is used to update the isEditableAnnotation callback
When the supplied callback is invalid it will throw a Error that contains a detailed error message.
Parameters
isEditableAnnotationCallbackIsEditableAnnotationCallbackReturns
voidExample
Only allow editing annotations from a specific creator name
instance.setIsEditableAnnotation((annotation) => annotation.creatorName === "Alice");Errors
Will throw an error when the supplied array is not valid.
This method is used to update the isEditableComment callback
When the supplied callback is invalid it will throw a Error that contains a detailed error message.
To learn more check this guide article.
Parameters
isEditableCommentCallbackIsEditableCommentCallbackReturns
voidExample
Only allow editing comments from a specific creator name
instance.setIsEditableComment((comment) => comment.creatorName === myCurrentUser.name);Errors
Will throw an error when the supplied array is not valid.
*** Standalone only ***
Sets the OCG visibility state.
This method makes the layers identified by
visibleLayerIdsvisible and hides every other layer in the document's layer list. Optional content groups that are not part of that list keep the visibility defined by the document.getLayersVisibilityState() returns the IDs of the currently visible layers, and createLayer() returns the ID of the layer it creates.
Parameters
layersVisibilityStateOCGLayersVisibilityStateThe OCG visibility state to set.
Returns
Promise<void>A promise that resolves when the OCG visibility state has been set.
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-USfalls back toen.See NutrientViewer.I18n.locales to get a list of all the available locales.
Parameters
localeLocale | string & {}The locale to set the app to. It must be one of NutrientViewer.I18n.locales.
Returns
Promise<void>Returns a promise that resolves once the locale is set.
Errors
Will throw an error when the locale does not exist, when no translations are bundled for it, or when its translations are bundled but the chunk carrying them could not be fetched. Only the fetch failure carries the underlying error as
error.cause.
setMaxMentionSuggestions
- Server
Set the maximum number of suggestions that will be shown when mentioning a user.
Parameters
maxMentionSuggestionsnumberThe maximum number of suggestions that will be shown when mentioning a user.
Returns
voidExample
instance.setMaxMentionSuggestions(5);
- setMeasurementPrecision(
precision:
| "whole"
| "oneDp"
| "twoDp"
| "threeDp"
| "fourDp"
| "1/2"
| "1/4"
| "1/8"
| "1/16",
): voidSet the precision value of all the newly created measurement annotations.
Parameters
precision"whole"
| "oneDp"
| "twoDp"
| "threeDp"
| "fourDp"
| "1/2"
| "1/4"
| "1/8"
| "1/16"Precision value
Returns
voidExample
instance.setMeasurementPrecision(NutrientViewer.MeasurementPrecision.THREE);
setMeasurementScale(
scale: NutrientViewer.MeasurementScale,
options?: { … },
): Promise<void>Set the default value of scale for all newly created measurement annotations.
Parameters
Scale value
options{ … }
OptionalOptional persistence options.
- OptionalcompoundUnits?: {
precision:
| "whole"
| "oneDp"
| "twoDp"
| "threeDp"
| "fourDp"
| "1/2"
| "1/4"
| "1/8"
| "1/16";
unitTo: "pt"
| "in"
| "mm"
| "cm"
| "ft"
| "m"
| "yd"
| "km"
| "mi";
}[]Compound (mixed-unit) chain stored with the scale. Standalone only.
- Optionalname?: string
Overrides the auto-generated scale name.
Returns
Promise<void>Example
instance.setMeasurementScale(new NutrientViewer.MeasurementScale({
unitFrom: NutrientViewer.MeasurementScaleUnitFrom.CENTIMETERS,
unitTo: NutrientViewer.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
enabledbooleanWhether to enable/disable snapping behaviour for creation of measurement annotations.
Returns
void
- setMeasurementValueConfiguration(
configurationCallback: MeasurementValueConfigurationCallback,
): voidParameters
configurationCallbackMeasurementValueConfigurationCallbackReturns
void
setMentionableUsers
- Server
Set a list of users that can be mentioned in comments.
Parameters
mentionableUsersMentionableUser[]An array of MentionableUser objects.
Returns
voidExample
instance.setMentionableUsers([
{ id: "1", name: "John Doe", displayName: "John", avatar: "https://example.com/avatar.png" },
{ id: "2", name: "Jane Doe", displayName: "Jane", avatar: "https://example.com/avatar.png" },
{ id: "3", name: "John Smith", displayName: "John", avatar: "https://example.com/avatar.png" },
]);
- setOnAnnotationResizeStart(
setOnAnnotationResizeStartCallback: AnnotationResizeStartCallback,
): voidThis method is used to update the setOnAnnotationResizeStart callback
When the supplied callback is invalid it will throw a NutrientViewer.Error that contains a detailed error message.
Parameters
setOnAnnotationResizeStartCallbackAnnotationResizeStartCallbackReturns
void
You can programmatically modify the properties of the comment just before it is created.
Parameters
callbackOnCommentCreationStartCallbackThe callback to set the values of created form fields programmatically.
Returns
voidExample
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
The callback to set the values of created form fields programmatically.
Returns
voidExample
instance.setOnWidgetAnnotationCreationStart((annotation, formField) => {
return { annotation: annotation.set('opacity', 0.7) };
});
setPageTabOrder
- setPageTabOrder(
pageIndex: number,
annotationIdsSortCallback: (
tabOrderedAnnotations: AnnotationsUnion[],
) => string[],
): Promise<void>Standalone*** Standalone only ***
This method is used to set or modify the tab order of annotations in a given page.
Using this method, it is possible to specify the order in which annotations are navigated when using the keyboard. The tab order should be provided as an array of annotation IDs, or determined by a callback function.
The method accepts a page index as the first argument, and a callback as the second. This callback will be called with an array of annotations in the page sorted by their current tab order, and should return an array of those annotations'
ids following the new tab order.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, and navigated accordingly.
Parameters
pageIndexnumberThe page index to set the tab order for.
annotationIdsSortCallback(tabOrderedAnnotations: AnnotationsUnion[]) => string[]A callback that will be invoked with the annotations in the current tab order, and is expected to return the annotation IDs in the new tab order.
Returns
Promise<void>Example
Set the tab order of annotations in page 0
instance.setPageTabOrder(0, currentTabOrderedAnnotations =>
["annotation-id-1", "annotation-id-2"]
);Set the tab order of annotations in page 0, with a radio form field
// 'radio-widget-id-2' will be rendered next to 'radio-widget-id-1', and navigated accordingly
instance.setPageTabOrder(0, currentTabOrderedAnnotations =>
["radio-widget-id-1", "annotation-id-1", "annotation-id-2", "radio-widget-id-2"]
);Sort page 1 annotations by their left position
instance.setPageTabOrder(
1,
currentTabOrderedAnnotations => currentTabOrderedAnnotations
.sort((a, b) => a.boundingBox.left - b.boundingBox.left)
.map(annotation => annotation.id)
);Errors
Will throw an error when the supplied tab order is not valid.
- setSearchState(
stateOrFunction:
| NutrientViewer.SearchState
| (
(
currentState: NutrientViewer.SearchState,
) => NutrientViewer.SearchState
),
): voidThis method is used to update the UI search state of the PDF editor.
When you pass in a 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 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
currentStatecan't change in between.When the supplied SearchState is invalid, this method will throw an Error that contains a detailed error message.
SearchState#minSearchQueryLength is a readonly property and cannot be changed. If the provided SearchState object includes a modified
minSearchQueryLengthproperty, a warning will be shown and only changes to other properties will be applied.Parameters
stateOrFunctionNutrientViewer.SearchState
| (
(
currentState: NutrientViewer.SearchState
) => NutrientViewer.SearchState
)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.
Returns
voidExample
Update values for the immutable search state object
const state = instance.SearchState;
const newState = state.set("isLoading", true);
instance.setSearchState(newState);Errors
Will throw an error when the supplied state is not valid.
setSelectedAnnotations(
annotationsOrAnnotationsIds?:
| NutrientViewer.Immutable.List<
string
| NutrientViewer.Annotations.Annotation<{ … }>,
>
| null,
): voidSelects annotations in the user interface. If
annotationOrAnnotationIdis empty, the current selection will be cleared instead.Parameters
annotationsOrAnnotationsIdsNutrientViewer.Immutable.List<
string
| NutrientViewer.Annotations.Annotation<{ … }>
>
| nullOptionalThe annotations model or annotations IDs you want to set as selected. If
nullis used, the current selection will be cleared instead.Returns
void
Updates the JWT (session token) and triggers server-backed re-authentication. Call this from onAuthFailed when tokens expire, or proactively before expiry to avoid auth failures.
This method isn't supported when loading app-provided documents with DWS Viewer API. That flow doesn't refresh the session after load.
Parameters
sessionstringThe new JWT token.
Returns
void
setSignaturesLTV
- Standalone
Adds LTV (Long Term Validation) information to an existing signature. See DigitalSignatures.SignaturesInfo.
Requires both the
Digital SignaturesandForm Viewing and Fillinglicense features. WithoutForm Viewing and Filling, signature form fields are not recognized in the document and this method resolves with an emptysignaturesarray — even on a signed document — and the signature validation status banner will not be shown.Additional information can be found in this guide article.
Parameters
Certificates used to sign the document.
Returns
Promise that resolves with a DigitalSignatures.SignaturesInfo.
Example
Add LTV information to an existing signature
instance.setSignaturesLTV(certificates)
.then(signaturesInfo => {
console.log(signaturesInfo.status)
if(signaturesInfo.signatures) {
const invalidSignatures = signaturesInfo.signatures
.filter(signature => !signature.ltv);
console.log(invalidSignatures);
}
});
- setStampAnnotationTemplates(
stateOrFunction:
| (
| NutrientViewer.Annotations.StampAnnotation
| NutrientViewer.Annotations.ImageAnnotation
)[]
| (
(
currentStampAnnotationTemplates: (
| NutrientViewer.Annotations.StampAnnotation
| NutrientViewer.Annotations.ImageAnnotation
)[],
) => (
| NutrientViewer.Annotations.StampAnnotation
| NutrientViewer.Annotations.ImageAnnotation
)[]
),
): voidThis 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
arraywith 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<NutrientViewer.Annotations.StampAnnotation | NutrientViewer.Annotations.ImageAnnotation>
Arrayas 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 ofcurrentStampAnnotationTemplatescan't change in between.When one of the supplied StampAnnotation or NutrientViewer.Annotations.ImageAnnotation is invalid, this method will throw a NutrientViewer.Error that contains a detailed error message.
Since
stampAnnotationTemplatesis a regular JavaScriptArray, it can be manipulated using standardArraymethods.Parameters
stateOrFunction(
| NutrientViewer.Annotations.StampAnnotation
| NutrientViewer.Annotations.ImageAnnotation
)[]
| (
(
currentStampAnnotationTemplates: (
| NutrientViewer.Annotations.StampAnnotation
| NutrientViewer.Annotations.ImageAnnotation
)[]
) => (
| NutrientViewer.Annotations.StampAnnotation
| NutrientViewer.Annotations.ImageAnnotation
)[]
)Either a new StampAnnotationTemplates
Arraywhich would overwrite the existing one, or a callback that will get invoked with the current stamp and image annotation templates and is expected to return the new stamp annotation stampsArray.Returns
voidExample
The new changes will be applied immediately
instance.setStampAnnotationTemplates(newStampAnnotationTemplates);
instance.stampAnnotationTemplates === newStampAnnotationTemplates; // => trueAdding a stamp annotation template.
const myStampAnnotationTemplate = new NutrientViewer.Annotations.StampAnnotation({
stampType: "Custom",
title: "My custom template title",
subtitle: "Custom subtitle",
boundingBox: new NutrientViewer.Geometry.Rect({ left: 0, top: 0, width: 192, height: 64 })
});
instance.setStampAnnotationTemplates(stampAnnotationTemplates => [ ...stampAnnotationTemplates, myStampAnnotationTemplate ]);Errors
Will throw an error when the supplied stamp annotation template
arrayis not valid.
- setStoredSignatures(
stateOrFunction:
| NutrientViewer.Immutable.List<
| NutrientViewer.Annotations.InkAnnotation
| NutrientViewer.Annotations.ImageAnnotation,
>
| (
(
annotations: NutrientViewer.Immutable.List<
| NutrientViewer.Annotations.InkAnnotation
| NutrientViewer.Annotations.ImageAnnotation,
>,
) => NutrientViewer.Immutable.List<
| NutrientViewer.Annotations.InkAnnotation
| NutrientViewer.Annotations.ImageAnnotation,
>
),
): Promise<void>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
pageIndexandboundingBoxis calculated at creation time. When selected via UI such annotations are used as template to create new NutrientViewer.Annotations.InkAnnotations and NutrientViewer.Annotations.ImageAnnotations.When you pass in a List of NutrientViewer.Annotations.InkAnnotation and NutrientViewer.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 NutrientViewer.Annotations.InkAnnotation and NutrientViewer.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.When the application doesn't have signatures in store this method will invoke 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 NutrientViewer.Error that contains a detailed error message.
Parameters
stateOrFunctionNutrientViewer.Immutable.List<
| NutrientViewer.Annotations.InkAnnotation
| NutrientViewer.Annotations.ImageAnnotation
>
| (
(
annotations: NutrientViewer.Immutable.List<
| NutrientViewer.Annotations.InkAnnotation
| NutrientViewer.Annotations.ImageAnnotation
>
) => NutrientViewer.Immutable.List<
| NutrientViewer.Annotations.InkAnnotation
| NutrientViewer.Annotations.ImageAnnotation
>
)a new
arrayof signatures which would overwrite the existing one, or a callback that will get invoked with the current toolbar items and is expected to return the newarrayof items.Returns
Promise<void>Example
Fetch and set a list of signatures
const signatures = fetch("/signatures")
.then(r => r.json())
.then(a => (
new NutrientViewer.Immutable.List(
a.map(NutrientViewer.Annotations.fromSerializableObject)
)
)
);
signatures.then(signatures => { instance.setStoredSignatures(signatures) });Use ES2015 arrow functions and the update callback to reduce boilerplate
instance.setStoredSignatures(signatures => signatures.reverse());Add a Signature to the existing list
const signature = new NutrientViewer.Annotations.InkAnnotation({
pageIndex: 0,
lines: NutrientViewer.Immutable.List([NutrientViewer.Immutable.List([new NutrientViewer.Geometry.DrawingPoint({ x: 0, y: 0 })])]),
boundingBox: new NutrientViewer.Geometry.Rect({ left: 0, top: 0, width: 100, height: 100 })
});
instance.setStoredSignatures(signatures => signatures.push(signature));Remove the first Signature from the list
instance.setStoredSignatures(signatures => signatures.shift());Errors
Will throw an error when the supplied items
arrayis not valid.
- setToolbarItems(
toolbarItemsOrFunction:
| ToolbarItem[]
| ((currentToolbarItems: ToolbarItem[]) => ToolbarItem[]),
): voidThis 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
arrayof 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
arrayof 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 ofcurrentToolbarItemscan't change in between.When one of the supplied ToolbarItem is invalid, this method will throw an Error that contains a detailed error message.
Since
itemsis a regular JavaScriptArrayof object literals it can be manipulated using standard array methods likeforEach,map,reduce,spliceand so on. Additionally you can use any 3rd party library for array manipulation like lodash or just.Parameters
toolbarItemsOrFunctionToolbarItem[] | ((currentToolbarItems: ToolbarItem[]) => ToolbarItem[])a new
arrayof ToolbarItems which would overwrite the existing one, or a callback that will get invoked with the current toolbar items and is expected to return the newarrayof items.Returns
voidExample
Reverse the order of the toolbar items
const items = instance.toolbarItems;
items.reverse();
instance.setToolbarItems(newState);Use ES2015 arrow functions and the update callback to reduce boilerplate
instance.setToolbarItems(items => items.reverse());The new changes will be applied immediately
instance.setToolbarItems(newItems);
instance.toolbarItems === newItems; // => trueAdding a button that's always visible on the right hand side of the
zoom-inbutton.const myButton = {
type: "custom",
id: "my-button",
title: "Test Button",
icon: "https://example.com/icon.jpg",
onPress() {
alert("test");
}
// mediaQueries is not defined so it will always be shown
};
instance.setToolbarItems(items => {
items.forEach((item, index) => {
if (item.name === "spacer") {
items.splice(index + 1, 0, myButton);
}
});
return items;
});Changing a property of a custom button
const myButton = {
type: "custom",
id: "my-button",
title: "Test Button",
icon: "https://example.com/icon.jpg",
disabled: true,
onPress() {
alert("test");
},
};
NutrientViewer.load({
toolbarItems: [...NutrientViewer.defaultToolbarItems, myButton],
// ...
}).then(instance => {
instance.setToolbarItems(items =>
items.map(item => {
if (item.id === "my-button") {
item.disabled = false;
}
return item;
})
);
});Errors
Will throw an error when the supplied items
arrayis not valid.
Set the UI customization config. This method allows you to change the UI configuration of an already mounted instance. The provided configuration will replace the previous configuration entirely.
In case of partial updates, you should merge the previous configuration with new changes.
Refer to the guide for more information and examples.
Parameters
configurationUI.ConfigurationThe new UI configuration to set.
Returns
voidExample
instance.setUI({
commentThread: () => ({
render: () => {
const div = document.createElement("div");
div.innerText = "Custom Comment Thread";
div.style.padding = "10px";
return div;
}
})
})
@public
- setViewState(
stateOrFunction:
| NutrientViewer.ViewState
| ((currentState: NutrientViewer.ViewState) => NutrientViewer.ViewState),
): voidThis method is used to update the UI state of the PDF editor.
When you pass in a 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 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
currentStatecan't change in between.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 "viewState.change". 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 "viewState.change" will only be triggered once. The "viewState.change" 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 ViewState is invalid, this method will throw an Error that contains a detailed error message.
Parameters
stateOrFunctionNutrientViewer.ViewState
| ((currentState: NutrientViewer.ViewState) => NutrientViewer.ViewState)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.
Returns
voidExample
Update values for the immutable state object
const state = instance.viewState;
const newState = state.set("currentPageIndex", 2);
instance.setViewState(newState);Use ES2015 arrow functions and the update callback to reduce boilerplate
instance.setViewState(state => state.set("currentPageIndex", 2));The state will be applied immediately
instance.setViewState(newState);
instance.viewState === newState; // => trueWhen the state is invalid, it will throw a NutrientViewer.Error
try {
// Non existing page index
instance.setViewState(state => state.set("currentPageIndex", 2000));
} catch (error) {
error.message; // => "The currentPageIndex set on the new ViewState is out of bounds.
// The index is expected to be in the range from 0 to 5 (inclusive)"
}Errors
Will throw an error when the supplied state is not valid.
- signDocument(
signaturePreparationData: SignatureCreationData | null,
twoStepSignatureCallbackOrSigningServiceData?:
| TwoStepSignatureCallback
| SigningServiceData,
): Promise<void>Digitally signs the document. On Standalone it can make sign the document with the certificates and private key provided by the user in DigitalSignatures.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
signaturePreparationDataSignatureCreationData | nullProperties to prepare the signature with.
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<void>Promise that resolves when the document is signed.
Example
Sign document with CMS signature (Standalone)
instance.signDocument(null, function({ hash, fileContents }) {
return new Promise(function(resolve, reject) {
const PKCS7Container = getPKCS7Container(hash, fileContents);
if (PKCS7Container != null) {
return resolve(PKCS7Container)
}
reject(new Error("Could not retrieve the PKCS7 container."))
})
}).then(function() {
console.log("Document signed!");
})Sign document (Server)
instance.signDocument(null, { signingToken: "My security token" })
.then(function() {
console.log("Document signed!");
})
Open the search box, fill in the search term, and start loading the search requests.
This will set the ViewState#interactionMode to NutrientViewer.InteractionMode.SEARCH so that the search box is visible.
Parameters
termstringThe search term.
Returns
voidExample
Start a search for the term
fooin the UIinstance.startUISearch("foo");
- textLinesForPageIndex(
pageIndex: number,
): Promise<NutrientViewer.Immutable.List<NutrientViewer.TextLine>>Load all TextLines for the specified
pageIndex. If there is no page at the given index, the list will be empty.Parameters
pageIndexnumberThe index of the page you want to extract text from.
Returns
A promise that resolves the text lines of the given page.
Enable actions like cut, copy, paste and duplicate for annotations using keyboard shortcuts
Cmd/Ctrl+X,Cmd/Ctrl+C,Cmd/Ctrl+VandCmd/Ctrl+Drespectively.Parameters
enabledbooleanWhether to enable/disable the clipboard actions.
Returns
void
- transformClientToPageSpace<
T extends NutrientViewer.Geometry.Rect
| NutrientViewer.Geometry.Point,
>(
rectOrPoint: T,
pageIndex: number,
): TTransforms a NutrientViewer.Geometry.Point or a NutrientViewer.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()orMouseEvent.clientX, etc.Use this transform when you receive events inside the main frame (The
documentof your application).Note: If you apply a CSS scale transformation to the mounting node of Nutrient Web SDK, this calculation will not work. In this case make sure to manually scale afterwards.
Type Parameters
Textends NutrientViewer.Geometry.Rect | NutrientViewer.Geometry.PointParameters
rectOrPointTThe rectangle or point that needs to be transformed that needs to be transformed
pageIndexnumberThe index of the page you want to have information about. If none is provided, the first page (pageIndex
0) will be used.Returns
The transformed point or rectangle.
Errors
Will throw an error when the supplied arguments is not valid.
- transformContentClientToPageSpace<
T extends NutrientViewer.Geometry.Rect
| NutrientViewer.Geometry.Point,
>(
rectOrPoint: T,
pageIndex: number,
): TTransforms a NutrientViewer.Geometry.Point or a NutrientViewer.Geometry.Rect from the client space inside the content frame to the PDF page space.
The content client space is relative to the NutrientViewer mounting container and the same coordinates that you receive by DOM APIs like
Element.getBoundingClientRect()orMouseEvent.clientX, etc. that originate within the Nutrient Web SDK's iframe.Use this transform when you receive events inside the content frame.
Type Parameters
Textends NutrientViewer.Geometry.Rect | NutrientViewer.Geometry.PointParameters
rectOrPointTThe rectangle or point that needs to be transformed that needs to be transformed
pageIndexnumberThe index of the page you want to have information about. If none is provided, the first page (pageIndex
0) will be used.Returns
The transformed point or rectangle.
Errors
Will throw an error when the supplied arguments is not valid.
- transformContentPageToClientSpace<
T extends NutrientViewer.Geometry.Rect
| NutrientViewer.Geometry.Point,
>(
rectOrPoint: T,
pageIndex: number,
): TTransforms a NutrientViewer.Geometry.Point or a NutrientViewer.Geometry.Rect from the PDF page space to the client space inside the content frame.
The content client space is relative to the NutrientViewer mounting container and the same coordinates that you receive by DOM APIs like
Element.getBoundingClientRect()orMouseEvent.clientX, etc. that originate within the Nutrient Web SDK's iframe.Use this transform when you want to position elements inside the NutrientViewer content frame.
Type Parameters
Textends NutrientViewer.Geometry.Rect | NutrientViewer.Geometry.PointParameters
rectOrPointTThe rectangle or point that needs to be transformed that needs to be transformed
pageIndexnumberThe index of the page you want to have information about. If none is provided, the first page (pageIndex
0) will be used.Returns
The transformed point or rectangle.
Errors
Will throw an error when the supplied arguments is not valid.
- transformPageToClientSpace<
T extends NutrientViewer.Geometry.Rect
| NutrientViewer.Geometry.Point,
>(
rectOrPoint: T,
pageIndex: number,
): TTransforms a NutrientViewer.Geometry.Point or a NutrientViewer.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()orMouseEvent.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 Nutrient Web SDK, this calculation will not work. In this case make sure to manually scale afterwards.
Type Parameters
Textends NutrientViewer.Geometry.Rect | NutrientViewer.Geometry.PointParameters
rectOrPointTThe rectangle or point that needs to be transformed that needs to be transformed
pageIndexnumberThe index of the page you want to have information about. If none is provided, the first page (pageIndex
0) will be used.Returns
The transformed point or rectangle.
Errors
Will throw an error when the supplied arguments is not valid.
- transformPageToRawSpace(
rect: NutrientViewer.Geometry.Rect,
pageIndex: number,
): NutrientViewer.Geometry.InsetTransforms a NutrientViewer 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 NutrientViewer page units) where thetopandbottomcoordinates 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
The rectangle to be transformed
pageIndexnumberThe index of the page you want to have information about.
Returns
The resulting transformed rectangle as inset coordinates.
Errors
Will throw an error when the supplied arguments is not valid.
- transformRawToPageSpace(
rawInset:
| NutrientViewer.Geometry.Inset
| [left: number, top: number, right: number, bottom: number],
pageIndex: number,
): NutrientViewer.Geometry.RectTransforms a raw PDF bounding rect from the PDF page space to NutrientViewer'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
rawInsetNutrientViewer.Geometry.Inset
| [left: number, top: number, right: number, bottom: number]The inset to be transformed
pageIndexnumberThe index of the page you want to have information about.
Returns
The resulting transformed rectangle.
Errors
Will throw an error when the supplied arguments is not valid.
Updates an object and changes its contents. This can be used for annotations, bookmarks, form fields, and comments.
If you need to ensure that changes are persisted by the backend, please refer to: Instance#ensureChangesSaved.
New changes will be made visible in the UI instantly.
Comments are immutable records, so update them with
.set()and pass the updated comment to this method.Parameters
Returns
Example
const instance = await NutrientViewer.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; // => trueUpdate a comment.
const instance = await NutrientViewer.load(configuration);
const comments = await instance.getComments();
const comment = comments.find((item) =>
(item.text.value ?? "").includes("Please review")
);
if (comment) {
const updatedComment = comment.set("text", {
format: comment.text.format,
value: "Reviewed and approved.",
});
await instance.update(updatedComment);
}
A mounted document instance.
You can generate an instance by using NutrientViewer.load.