API for React Native PDF viewer

TypeScript

Apryse React Native now has support for TypeScript. Since not all customers use the language, the typings used in this document will be described using normal JavaScript types. For TypeScript users, type information is automatically provided while coding. They can also be found in our TypeScript source files.

RNPdftron

RNPdftron contains static methods for global library initialization, configuration, and utility methods.

initialize

Initializes Apryse SDK with your Apryse commercial license key. You can run Apryse in demo mode by passing an empty string.

Parameters:

NameTypeDescription
licenseKeystringyour Apryse license key

ScriptRNPdftron.initialize('your_license_key');

enableJavaScript

Enables JavaScript for Apryse SDK, by default it is enabled.

Parameters:

NameTypeDescription
enabledboolwhether to enable or disable JavaScript

ScriptRNPdftron.enableJavaScript(true);

getVersion

Gets the current PDFNet version.

Returns a Promise.

Promise Parameters:

NameTypeDescription
versionstringcurrent PDFNet version

JavaScript

1RNPdftron.getVersion().then((version) => {
2 console.log("Current PDFNet version:", version);
3});

getPlatformVersion

Gets the version of current platform (Android/iOS).

Returns a Promise.

Promise Parameters:

NameTypeDescription
platformVersionstringcurrent platform version (Android/iOS)

JavaScript

1RNPdftron.getPlatformVersion().then((platformVersion) => {
2 console.log("App currently running on:", platformVersion);
3});

getSystemFontList

Gets the font list available on the OS (Android only). This is typically useful when you are mostly working with non-ASCII characters in the viewer.

Returns a Promise.

Promise Parameters:

NameTypeDescription
fontListstringthe font list available on Android

JavaScript

1RNPdftron.getSystemFontList().then((fontList) => {
2 console.log("OS font list:", fontList);
3});

clearRubberStampCache

Clear the information and bitmap cache for rubber stamps (Android only). This is typically useful when the content of rubber stamps has been changed in the viewer.

Returns a promise.

JavaScript

1RNPdftron.clearRubberStampCache().then(() => {
2 console.log("Rubber stamp cache cleared");
3});

encryptDocument

Encrypts (password-protects) a document. Note: This function does not lock the document and cannot be used while the document is opened in the viewer.

Parameters:

NameTypeDescription
file pathstringthe local file path to the file
passwordstringthe password you would like to set
current passwordstringthe current password, use empty string if no password

Returns a promise.

Example:

JavaScript

1RNPdftron.encryptDocument("/sdcard/Download/new.pdf", "1111", "").then(() => {
2 console.log("done password");
3});

pdfFromOfficeTemplate

Generates a PDF using a template in the form of an Office document and replacement data in the form of a JSON object. For more information please see our template guide.

Parameters:

NameTypeDescription
docxPathstringthe local file path to the template file
jsonstringthe replacement data in the form of a JSON object

Returns a Promise.

Promise Parameters:

NameTypeDescription
resultPdfPathstringthe local file path to the generated PDF

The user is responsible for cleaning up the temporary file that is generated.

Example:

JavaScript

1RNPdftron.pdfFromOfficeTemplate("/sdcard/Download/red.docx", json).then((resultPdfPath) => {
2 console.log(resultPdfPath);
3});

DocumentView - Props

A React component for displaying documents of different types such as PDF, docx, pptx, xlsx and various image formats.

Open a Document

document

string, required

The path or url to the document.

Example:

JavaScript

1<DocumentView
2 document={'https://pdftron.s3.amazonaws.com/downloads/pl/PDFTRON_about.pdf'}
3/>

password

string, optional

The password of the document, if any.

Example:

JavaScript

1<DocumentView
2 password={'password'}
3/>

isBase64String

bool, optional, defaults to false

If true, document prop will be treated as a base64 string. If it is not the base64 string of a pdf file, base64FileExtension is required.

When viewing a document initialized with a base64 string (i.e. a memory buffer), a temporary file is created on Android and iOS.

JavaScript

1<DocumentView
2 isBase64String={true}
3 document={'...'} // base 64 string
4/>

base64FileExtension

string, required if using base64 string of a non-pdf file, defaults to ".pdf"

The file extension for the base64 string in document, if isBase64String is true.

JavaScript

1<DocumentView
2 isBase64String={true}
3 document={'...'} // base 64 string
4 base64FileExtension={'.jpeg'}
5/>

customHeaders

object, optional

Defines custom headers to use with HTTP/HTTPS requests.

JavaScript

1<DocumentView
2 isBase64String={true}
3 document={'...'} // base 64 string
4/>

readOnly

bool, optional, defaults to false

Defines whether the viewer is read-only. If true, the UI will not allow the user to change the document.

JavaScript

1<DocumentView
2 readOnly={true}
3/>

onDocumentLoaded

function, optional

This function is called when the document finishes loading.

JavaScript

1<DocumentView
2 onDocumentLoaded = {(path) => {
3 console.log('The document has finished loading:', path);
4 }}
5/>

onDocumentError

function, optional

This function is called when document opening encounters an error.

JavaScript

1<DocumentView
2 onDocumentError = {(error) => {
3 console.log('Error occured during document opening:', error);
4 }}
5/>

UI Customization

disabledElements

array of string, optional, defaults to none

Defines buttons to be disabled for the viewer. Strings should be Config.Buttons constants.

JavaScript

1<DocumentView
2 disabledElements={[Config.Buttons.userBookmarkListButton]}
3/>

disabledTools

array of string, optional, defaults to none

Defines tools to be disabled for the viewer. Strings should be Config.Tools constants.

JavaScript

1<DocumentView
2 disabledTools={[Config.Tools.annotationCreateLine, Config.Tools.annotationCreateRectangle]}
3/>

onToolChanged

function, optional

This function is called when the current tool changes to a new tool

Parameters:

NameTypeDescription
previousToolstring the previous tool (one of the Config.Tools constants or "unknown tool"), representing the tool before change
toolstringthe current tool (one of the Config.Tools constants or "unknown tool"), representing the current tool

JavaScript

1<DocumentView
2 onToolChanged = {({previousTool, tool}) => {
3 console.log('Tool has been changed from', previousTool, 'to', tool);
4 }}
5/>

leadingNavButtonIcon

string, optional

The file name of the icon to be used for the leading navigation button. The button will use the specified icon if it is valid, and the default icon otherwise.

Example:

JavaScript

1<DocumentView
2 leadingNavButtonIcon={Platform.OS === 'ios' ? 'ic_close_black_24px.png' : 'ic_arrow_back_white_24dp'}
3/>

Note: to add the image file to your application, please follow the steps below:

1. Android

Add the image resource to the drawable directory in example/android/app/src/main/res. For details about supported file types and potential compression, check out this guide.

Apryse Docs Image

2. Now you can use the image in the viewer. For example, if you add button_close.png to drawable, you could use 'button_close' in leadingNavButtonIcon.

iOS

1. After pods has been installed, open the .xcworkspace file for this application in Xcode (in this case, it's example.xcworkspace), and navigate through the list below. This would allow you to add resources, in this case, an image, to your project.

  • "Project navigator"
  • "example" (or the app name)
  • "Build Phases"
  • "Copy Bundle Resources"
  • "+".
Apryse Docs Image

2. Now you can use the image in the viewer. For example, if you add button_open.png to the bundle, you could use 'button_open.png' in leadingNavButtonIcon.

showLeadingNavButton

bool, optional, defaults to true

Defines whether to show the leading navigation button.

JavaScript

1<DocumentView
2 showLeadingNavButton={true}
3/>

onLeadingNavButtonPressed

function, optional

This function is called when the leading navigation button is pressed.

JavaScript

1<DocumentView
2 onLeadingNavButtonPressed = {() => {
3 console.log('The leading nav has been pressed');
4 }}
5/>

documentSliderEnabled

bool, optional, defaults to true

Defines whether the document slider of the viewer is enabled.

JavaScript

1<DocumentView
2 documentSliderEnabled={false}
3/>

hideViewModeItems

array of string, optional, defaults to none.

Defines view mode items to be hidden in the view mode dialog. Strings should be Config.ViewModePickerItem constants.

JavaScript

1<DocumentView
2 hideViewModeItems={[
3 Config.ViewModePickerItem.Crop,
4 Config.ViewModePickerItem.Rotation,
5 Config.ViewModePickerItem.ColorMode
6 ]}
7/>

Toolbar Customization

topToolbarEnabled

bool, optional, defaults to true

Deprecated. Use hideTopAppNavBar prop instead.

bottomToolbarEnabled

bool, optional, defaults to true

Defines whether the bottom toolbar of the viewer is enabled.

JavaScript

1<DocumentView
2 bottomToolbarEnabled={false}
3/>

annotationToolbars

array of objects, options (one of Config.DefaultToolbars constants or custom toolbar object)

Defines custom toolbars. If passed in, the default toolbars will no longer appear. It is possible to mix and match with default toolbars. See example below:

JavaScript

1const myToolbar = {
2 [Config.CustomToolbarKey.Id]: 'myToolbar',
3 [Config.CustomToolbarKey.Name]: 'myToolbar',
4 [Config.CustomToolbarKey.Icon]: Config.ToolbarIcons.FillAndSign,
5 [Config.CustomToolbarKey.Items]: [Config.Tools.annotationCreateArrow, Config.Tools.annotationCreateCallout, Config.Buttons.undo]
6};
7...
8<DocumentView
9 annotationToolbars={[Config.DefaultToolbars.Annotate, myToolbar]}
10/>

hideDefaultAnnotationToolbars

array of strings, optional, defaults to none

Defines which default annotation toolbars should be hidden. Note that this prop should be used when annotationToolbars is not defined. Strings should be Config.DefaultToolbars constants.

JavaScript

1<DocumentView
2 hideDefaultAnnotationToolbars={[Config.DefaultToolbars.Annotate, Config.DefaultToolbars.Favorite]}
3/>

hideAnnotationToolbarSwitcher

bool, optional, defaults to false

Defines whether to show the toolbar switcher in the top toolbar.

JavaScript

1<DocumentView
2 hideAnnotationToolbarSwitcher={false}
3/>

hideTopToolbars

bool, optional, defaults to false

Defines whether to hide both the top app nav bar and the annotation toolbar.

JavaScript

1<DocumentView
2 hideTopToolbars={false}
3/>

hideTopAppNavBar

bool, optional, defaults to false

Defines whether to hide the top navigation app bar.

JavaScript

1<DocumentView
2 hideTopAppNavBar={true}
3/>

hideToolbarsOnTap

bool, optional, defaults to true

Defines whether an unhandled tap in the viewer should toggle the visibility of the top and bottom toolbars. When false, the top and bottom toolbar visibility will not be toggled and the page content will fit between the bars, if any.

JavaScript

1<DocumentView
2 hideToolbarsOnTap={false}
3/>

topAppNavBarRightBar

array of strings, optional, iOS only

Customizes the right bar section of the top app nav bar. If passed in, the default right bar section will not be used. Strings should be Config.Buttons constants.

JavaScript

1<DocumentView
2 topAppNavBarRightBar={[Config.Buttons.reflowButton, Config.Buttons.outlineListButton]}
3/>

bottomToolbar

array of strings, optional, only the outline list, thumbnail list, share, view mode, search, and reflow buttons are supported on Android

Defines a custom bottom toolbar. If passed in, the default bottom toolbar will not be used. Strings should be Config.Buttons constants.

JavaScript

1<DocumentView
2 bottomToolbar={[Config.Buttons.reflowButton, Config.Buttons.outlineListButton]}
3/>

padStatusBar

bool, optional, defaults to false, Android only

Defines whether the viewer will add padding to take account of the system status bar.

JavaScript

1<DocumentView
2 padStatusBar={true}
3/>

Layout

fitMode

string, optional, default value is 'FitWidth'

Defines the fit mode (default zoom level) of the viewer. String should be one of Config.FitMode constants.

JavaScript

1<DocumentView
2 fitMode={Config.FitMode.FitPage}
3/>

layoutMode

string, optional, default value is 'Continuous'

Defines the layout mode of the viewer. String should be one of Config.LayoutMode constants.

JavaScript

1<DocumentView
2 layoutMode={Config.LayoutMode.FacingContinuous}
3/>

onLayoutChanged

function, optional

This function is called when the layout of the viewer has been changed.

JavaScript

1<DocumentView
2 onLayoutChanged = {() => {
3 console.log('Layout has been updated.');
4 }}
5/>

Page

initialPageNumber

number, optional

Defines the initial page number that viewer displays when the document is opened. Note that page numbers are 1-indexed.

JavaScript

1<DocumentView
2 initialPageNumber={5}
3/>

pageNumber

number, optional

Defines the currently displayed page number. Different from initialPageNumber, changing this prop value at runtime will change the page accordingly.

JavaScript

1<DocumentView
2 pageNumber={5}
3/>

pageChangeOnTap

bool, optional, defaults to true

Defines whether the viewer should change pages when the user taps the edge of a page, when the viewer is in a horizontal viewing mode.

JavaScript

1<DocumentView
2 pageChangeOnTap={true}
3/>

pageIndicatorEnabled

bool, optional, defaults to true

Defines whether to show the page indicator for the viewer.

JavaScript

1<DocumentView
2 pageIndicatorEnabled={true}
3/>

keyboardShortcutsEnabled

bool, optional, defaults to true, iOS only

Defines whether the keyboard shortcuts of the viewer are enabled.

JavaScript

1<DocumentView
2 keyboardShortcutsEnabled={false}
3/>

onPageChanged

function, optional

This function is called when the page number has been changed.

Parameters:

NameTypeDescription
previousPageNumberintthe previous page number
pageNumberintthe current page number

JavaScript

1<DocumentView
2 onPageChanged = {({previousPageNumber, pageNumber}) => {
3 console.log('Page number changes from', previousPageNumber, 'to', pageNumber);
4 }}
5/>

Zoom

onZoomChanged

function, optional

This function is called when the zoom scale has been changed.

Parameters:

NameTypeDescription
zoomdoublethe current zoom ratio of the document

JavaScript

1<DocumentView
2 onZoomChanged = {(zoom) => {
3 console.log('Current zoom ratio is', zoom);
4 }}
5/>

onZoomFinished

function, optional

This function is called when a zooming has been finished. For example, if zoom via gesture, this is called on gesture release.

Parameters:

NameTypeDescription
zoomdoublethe current zoom ratio of the document

JavaScript

1<DocumentView
2 onZoomFinished = {(zoom) => {
3 console.log('Current zoom ratio is', zoom);
4 }}

Scroll

horizontalScrollPos

number, optional

Defines the horizontal scroll position in the current document viewer.

JavaScript

1<DocumentView
2 horizontalScrollPos={50}
3/>

verticalScrollPos

number, optional

Defines the vertical scroll position in the current document viewer.

JavaScript

1<DocumentView
2 verticalScrollPos={50}
3/>

onScrollChanged

function, optional

This function is called when the scroll position has been changed.

Parameters:

NameTypeDescription
horizontalnumberthe horizontal position of the scroll
verticalnumberthe vertical position of the scroll

JavaScript

1<DocumentView
2 onScrollChanged = {({horizontal, vertical}) => {
3 console.log('Current scroll position is', horizontal, 'horizontally, and', vertical, 'vertically.');
4 }}

Reflow

imageInReflowEnabled

bool, optional, defaults to true

Whether to show images in reflow mode.

JavaScript

1<DocumentView
2 imageInReflowEnabled={false}
3/>

reflowOrientation

string, optional, default value is 'Horizontal'. Android only.

Sets the scrolling direction of the reflow control. Strings should be Config.ReflowOrientation constants.

JavaScript

1<DocumentView
2 reflowOrientation={Config.ReflowOrientation.Vertical}
3/>

Annotation Menu

hideAnnotationMenu

array of strings, optional, defaults to none

Defines annotation types that will not show in the annotation (long-press) menu. Strings should be Config.Tools constants.

JavaScript

1<DocumentView
2 hideAnnotationMenu={[Config.Tools.annotationCreateArrow, Config.Tools.annotationEraserTool]}
3/>

annotationMenuItems

array of strings, optional, default contains all the items

Defines the menu items that can show when an annotation is selected. Strings should be Config.AnnotationMenu constants.

JavaScript

1<DocumentView
2 annotationMenuItems={[Config.AnnotationMenu.search, Config.AnnotationMenu.share]}
3/>

overrideAnnotationMenuBehavior

array of strings, optional, defaults to none

Defines the menu items that will skip default behavior when pressed. Strings should be Config.AnnotationMenu constants. They will still be displayed in the annotation menu, and the function onAnnotationMenuPress will be called where custom behavior can be implemented.

JavaScript

1<DocumentView
2 overrideAnnotationMenuBehavior={[Config.AnnotationMenu.copy]}
3/>

onAnnotationMenuPress

function, optional

This function is called when an annotation menu item passed in to overrideAnnotationMenuBehavior is pressed.

Parameters:

NameTypeDescription
annotationMenustringOne of Config.AnnotationMenu constants, representing which item has been pressed
annotationsarrayAn array of {id: string, pageNumber: number, type: string, rect: object} objects, where id is the annotation identifier, pageNumber is the page number, type is one of the Config.Tools constants and rect={x1, y1, x2, y2} specifies the annotation's screen rect

JavaScript

1<DocumentView
2 onAnnotationMenuPress = {({annotationMenu, annotations}) => {
3 console.log('Annotation menu item', annotationMenu, 'has been pressed');
4 annotations.forEach(annotation => {
5 console.log('The id of selected annotation is', annotation.id);
6 console.log('The page number of selected annotation is', annotation.pageNumber);
7 console.log('The type of selected annotation is', annotation.type);
8 console.log('The lower left corner of selected annotation is', annotation.x1, annotation.y1);
9 });
10 }}
11/>

Long Press Menu

longPressMenuEnabled

bool, optional, defaults to true

Defines whether to show the popup menu of options when the user long presses on text or blank space on the document.

JavaScript

1<DocumentView
2 longPressMenuEnabled={true}
3/>

longPressMenuItems

array of strings, optional, default contains all the items

Defines menu items that can be shown when long pressing on text or blank space. Strings should be Config.LongPressMenu constants.

JavaScript

1<DocumentView
2 longPressMenuItems={[Config.LongPressMenu.copy, Config.LongPressMenu.read]}
3/>

overrideLongPressMenuBehavior

array of strings, optional, defaults to none

Defines the menu items on long press that will skip default behavior when pressed. Strings should be Config.LongPressMenu constants. They will still be displayed in the long press menu, and the function onLongPressMenuPress will be called where custom behavior can be implemented.

JavaScript

1<DocumentView
2 overrideLongPressMenuBehavior={[Config.LongPressMenu.search]}
3/>

onLongPressMenuPress

function, optional

This function is called if the pressed long press menu item is passed in to overrideLongPressMenuBehavior

Parameters:

NameTypeDescription
longPressMenustringOne of Config.LongPressMenu constants, representing which item has been pressed
longPressTextstringthe selected text if pressed on text, empty otherwise

JavaScript

1<DocumentView
2 onLongPressMenuPress = {({longPressMenu, longPressText}) => {
3 console.log('Long press menu item', longPressMenu, 'has been pressed');
4 if (longPressText !== '') {
5 console.log('The selected text is', longPressText);
6 }
7 }}
8/>

Custom Behavior

overrideBehavior

array of string, optional, defaults to none

Defines actions that will skip default behavior, such as external link click. Strings should be Config.Actions constants. The function onBehaviorActivated will be called where custom behavior can be implemented, whenever the defined actions occur.

JavaScript

1<DocumentView
2 overrideBehavior={[Config.Actions.linkPress]}
3/>

onBehaviorActivated

function, optional

This function is called if the activated behavior is passed in to overrideBehavior

Parameters:

NameTypeDescriptionactionstringOne of Config.Actions constants, representing which action has been activateddataobjectA JSON object that varies depending on the action

Data param table:

NameTypeDescription
actionstringOne of Config.Actions constants, representing which action has been activated
dataobjectA JSON object that varies depending on the action

Data param table:

ActionData param
Config.Actions.linkPress{url: string}
Config.Actions.stickyNoteShowPopUp{id: string, pageNumber: number, type: string, rect: {x1: number, y1: number, x2: number, y2: number}}

JavaScript

1<DocumentView
2 onBehaviorActivated = {({action, data}) => {
3 console.log('Activated action is', action);
4 if (action === Config.Actions.linkPress) {
5 console.log('The external link pressed is', data.url);
6 } else if (action === Config.Actions.stickyNoteShowPopUp) {
7 console.log('Sticky note has been activated, but it would not show a pop up window.');
8 }
9 }}
10/>

Multi-tab

multiTabEnabled

bool, optional, defaults to false

Defines whether viewer will use tabs in order to have more than one document open simultaneously (like a web browser). Changing the document prop value will cause a new tab to be opened with the associated file.

JavaScript

1<DocumentView
2 multiTabEnabled={true}
3/>

tabTitle

string, optional, default is the file name

Set the tab title if multiTabEnabled is true.

JavaScript

1<DocumentView
2 multiTabEnabled={true} // requirement
3 tabTitle={'tab1'}
4/>

maxTabCount

number, optional, defaults to unlimited

Sets the limit on the maximum number of tabs that the viewer could have at a time. Open more documents after reaching this limit will overwrite the old tabs.

JavaScript

1<DocumentView
2 multiTabEnabled={true} // requirement
3 maxTabCount={5}
4/>

Collaboration

collabEnabled

bool, optional, defaults to false

Defines whether to enable realtime collaboration. If true then currentUser must be set as well for collaboration mode to work. Feature set may vary between local and collaboration mode

JavaScript

1<DocumentView
2 collabEnabled={true}
3 currentUser={'Pdftron'}
4/>

currentUser

string, required if collabEnabled is set to true

Defines the current user. Created annotations will have their title (author) set to this string.

JavaScript

1<DocumentView
2 collabEnabled={true}
3 currentUser={'Pdftron'}
4/>

currentUserName

string, optional

Defines the current user name. Will set the user name only if collabEnabled is true and currentUser is defined. This should be used only if you want the user's display name to be different than the annotation's title/author (in the case that currentUser is an ID rather than a human-friendly name.)

JavaScript

1<DocumentView
2 collabEnabled={true}
3 currentUser={'Pdftron'}
4 currentUserName={'Hello_World'}
5/>

Annotations

annotationPermissionCheckEnabled

bool, optional, defaults to false

Defines whether an annotation's permission flags will be respected when it is selected. For example, a locked annotation can not be resized or moved.

JavaScript

1<DocumentView
2 annotationPermissionCheckEnabled={true}
3/>

annotationAuthor

string, optional

Defines the author name for all annotations created on the current document. Exported xfdfCommand will include this piece of information.

JavaScript

1<DocumentView
2 annotationAuthor={'Apryse'}
3/>

continuousAnnotationEditing

bool, optional, defaults to true

If true, the active annotation creation tool will remain in the current annotation creation tool. Otherwise, it will revert to the "pan tool" after an annotation is created.

JavaScript

1<DocumentView
2 continuousAnnotationEditing={true}
3/>

selectAnnotationAfterCreation

bool, optional, defaults to true

Defines whether an annotation is selected after it is created. On iOS, this functions for shape and text markup annotations only.

JavaScript

1<DocumentView
2 selectAnnotationAfterCreation={true}
3/>

onExportAnnotationCommand

function, optional

This function is called if a change has been made to annotations in the current document. Unlike onAnnotationChanged, this function has an XFDF command string as its parameter. If you are modifying or deleting multiple annotations, then on Android the function is only called once, and on iOS it is called for each annotation.

Parameters:

NameTypeDescription
actionstringthe action that occurred (add, delete, modify)
xfdfCommand stringan xfdf string containing info about the edit
annotationsarrayan array of annotation data. When collaboration is enabled data comes in the format {id: string}, otherwise the format is {id: string, pageNumber: number, type: string}. In both cases, the data represents the annotations that have been changed. Type is one of the Config.Tools constants

Known Issues
On iOS, there is currently a bug that prevents the last XFDF from being retrieved when modifying annotations while collaboration mode is enabled.

JavaScript

1<DocumentView
2 onExportAnnotationCommand = {({action, xfdfCommand, annotations}) => {
3 console.log('Annotation edit action is', action);
4 console.log('The exported xfdfCommand is', xfdfCommand);
5 annotations.forEach((annotation) => {
6 console.log('Annotation id is', annotation.id);
7 if (!this.state.collabEnabled) {
8 console.log('Annotation pageNumber is', annotation.pageNumber);
9 console.log('Annotation type is', annotation.type);
10 }
11 });
12 }}
13 collabEnabled={this.state.collabEnabled}
14 currentUser={'Pdftron'}
15/>

onAnnotationsSelected

function, optional

This function is called when an annotation(s) is selected.

Parameters:

NameTypeDescription
annotationsarrayarray of annotation data in the format {id: string, pageNumber: number, type: string, rect: {x1: number, y1: number, x2: number, y2: number}}, representing the selected annotations. Type is one of the Config.Tools constants

JavaScript

1<DocumentView
2 onAnnotationsSelected = {({annotations}) => {
3 annotations.forEach(annotation => {
4 console.log('The id of selected annotation is', annotation.id);
5 console.log('It is in page', annotation.pageNumber);
6 console.log('Its type is', annotation.type);
7 console.log('Its lower left corner has coordinate', annotation.rect.x1, annotation.rect.y1);
8 });
9 }}
10/>

onAnnotationChanged

function, optional

This function is called if a change has been made to an annotation(s) in the current document.

Parameters:

NameTypeDescription
actionstringthe action that occurred (add, delete, modify)
annotationsarrayarray of annotation data in the format {id: string, pageNumber: number, type: string}, representing the annotations that have been changed. Type is one of the Config.Tools constants

JavaScript

1<DocumentView
2 onAnnotationChanged = {({action, annotations}) => {
3 console.log('Annotation edit action is', action);
4 annotations.forEach(annotation => {
5 console.log('The id of changed annotation is', annotation.id);
6 console.log('It is in page', annotation.pageNumber);
7 console.log('Its type is', annotation.type);
8 });
9 }}
10/>

onFormFieldValueChanged

function, optional

This function is called if a change has been made to form field values.

Parameters:

NameTypeDescription
fields arrayarray of field data in the format {fieldName: string, fieldValue: string}, representing the fields that have been changed

JavaScript

1<DocumentView
2 onFormFieldValueChanged = {({fields}) => {
3 console.log('Annotation edit action is', action);
4 annotations.forEach(annotation => {
5 console.log('The id of changed annotation is', annotation.id);
6 console.log('It is in page', annotation.pageNumber);
7 });
8 }}
9/>

annotationListEditingEnabled

bool, optional, Android only, default value is true

If document editing is enabled, then this value determines if the annotation list is editable.

JavaScript

1<DocumentView
2 annotationListEditingEnabled={true}
3/>

Bookmark

onBookmarkChanged

function, optional

This function is called if a change has been made to user bookmarks.

Parameters:

NameTypeDescription
bookmarkJson stringthe list of current bookmarks in JSON format

JavaScript

1<DocumentView
2 onBookmarkChanged = {({bookmarkJson}) => {
3 console.log('Bookmarks have been changed. Current bookmark collection is', bookmarkJson);
4 }}
5/>

userBookmarksListEditingEnabled

bool, optional, default value is true

Defines whether the bookmark list can be edited. If the viewer is readonly then bookmarks on Android are still editable but are saved to the device rather than the PDF.

JavaScript

1<DocumentView
2 userBookmarksListEditingEnabled={true}
3/>

Signature

signSignatureFieldsWithStamps

bool, optional, defaults to false

Defines whether signature fields will be signed with image stamps. This is useful if you are saving XFDF to remote source.

JavaScript

1<DocumentView
2 signSignatureFieldsWithStamps={true}
3/>

showSavedSignatures

bool, optional, defaults to true

Defines whether to show saved signatures for re-use when using the signing tool.

JavaScript

1<DocumentView
2 showSavedSignatures={true}
3/>

Thumbnail Browser

hideThumbnailFilterModes

array of strings, optional

Defines filter modes that should be hidden in the thumbnails browser. Strings should be Config.ThumbnailFilterMode constants

JavaScript

1<DocumentView
2 hideThumbnailFilterModes={[Config.ThumbnailFilterMode.Annotated]}
3/>

thumbnailViewEditingEnabled

bool, optional, defaults to true

Defines whether user can modify the document using the thumbnail view (e.g. add/remove/rotate pages).

JavaScript

1<DocumentView
2 thumbnailViewEditingEnabled={true}
3/>
4

Text Selection

onTextSearchStart

function, optional

This function is called immediately before a text search begins, either through user actions, or function calls such as findText.

JavaScript

1<DocumentView
2 onTextSearchStart = {() => {
3 console.log('Text search has started');
4 }}
5/>

onTextSearchResult

function, optional

This function is called after a text search is finished or canceled.

Parameters:

NameTypeDescription
foundboolwhether a result is found. If no, it could be caused by not finding a matching result in the document, invalid text input, or action cancellation (user actions or cancelFindText )
textSelectionobjectthe text selection, in the format {html: string, unicode: string, pageNumber: number, quads: [[{x: number, y: number}, {x: number, y: number}, {x: number, y: number}, {x: number, y: number}], ...]}. If no such selection could be found, this would be null

quads indicate the quad boundary boxes for the selection, which could have a size larger than 1 if selection spans across different lines. Each quad have 4 points with x, y coordinates specified in number, representing a boundary box. The 4 points are in counter-clockwise order, though the first point is not guaranteed to be on lower-left relatively to the box.

JavaScript

1<DocumentView
2 onTextSearchResult = {({found, textSelection}) => {
3 if (found) {
4 console.log('Found selection on page', textSelection.pageNumber);
5 for (let i = 0; i < textSelection.quads.length; i ++) {
6 const quad = textSelection.quads[i];
7 console.log('selection boundary quad', i);
8 for (const quadPoint of quad) {
9 console.log('A quad point has coordinates', quadPoint.x, quadPoint.y);
10 }
11 }
12 }
13 }}
14/>

Others

useStylusAsPen

bool, optional, defaults to true

Defines whether a stylus should act as a pen when in pan mode. If false, it will act as a finger.

JavaScript

1<DocumentView
2 useStylusAsPen={true}
3/>

followSystemDarkMode

bool, optional, Android and iOS 13+ only, defaults to true

Defines whether the UI will appear in a dark color when the system is dark mode. If false, it will use viewer setting instead.

JavaScript

1<DocumentView
2 followSystemDarkMode={false}
3/>

autoSaveEnabled

bool, optional, defaults to true

Defines whether document is automatically saved by the viewer.

JavaScript

1<DocumentView
2 autoSaveEnabled={true}
3/>

restrictDownloadUsage

bool, optional, defaults to false

Defines whether to restrict data usage when viewing online PDFs.

JavaScript

1<DocumentView
2 restrictDownloadUsage={true}
3/>

pageStackEnabled

bool, optional, defaults to true, Android only

Defines whether the page stack navigation buttons will appear in the viewer.

JavaScript

1<DocumentView
2 pageStackEnabled={false}
3/>

showQuickNavigationButton

bool, optional, defaults to true, Android only

Defines whether the quick navigation buttons will appear in the viewer.

JavaScript

1<DocumentView
2 showQuickNavigationButton={false}
3/>

showNavigationListAsSidePanelOnLargeDevices

bool, optional, defaults to true on Android and false on iOS

Defines whether the navigation list will be displayed as a side panel on large devices such as iPads and tablets.

JavaScript

1<DocumentView
2 showNavigationListAsSidePanelOnLargeDevices={true}
3/>

DocumentView - Methods

Document

getDocumentPath

Returns the path of the current document. If isBase64String is true, this would be the path to the temporary pdf file converted from the base64 string in document.

Returns a Promise.

Promise Parameters:

NameTypeDescription
pathstringthe document path

JavaScript

1this._viewer.getDocumentPath().then((path) => {
2 console.log('The path to current document is: ' + path);
3});

saveDocument

Saves the current document. If isBase64String is true, this would be the base64 string encoded from the temporary pdf file, which is created from the base64 string in document.

Returns a Promise.

Promise Parameters:

NameTypeDescription
filePathstringthe location of the saved document, or the base64 string of the pdf in the case of base64

JavaScript

1this._viewer.saveDocument().then((filePath) => {
2 console.log('saveDocument:', filePath);
3});

UI Customization

setColorPostProcessMode

Sets the color post processing transformation mode for the viewer.

Parameters:

NameTypeDescription
colorPostProcessModestringcolor post processing transformation mode, should be a Config.ColorPostProcessMode constant

JavaScript

1this._viewer.setColorPostProcessMode(Config.ColorPostProcessMode.NightMode);

setColorPostProcessColors

Sets the white and black color for the color post processing transformation.

Parameters:

NameTypeDescription
whiteColorobjectthe white color for the color post processing transformation, in the format {red: number, green: number, blue: number}. alpha could be optionally included (only Android would apply alpha), and all numbers should be in range [0, 255]
blackColorobjectthe black color for the color post processing transformation, in the same format as whiteColor

JavaScript

1const whiteColor = {"red": 0, "green": 0, "blue": 255};
2const blackColor = {"red": 255, "green": 0, "blue": 0};
3this._viewer.setColorPostProcessColors(whiteColor, blackColor);

Annotation Tools

setToolMode

Sets the current tool mode.

Parameters:

NameTypeDescription
toolModestringOne of Config.Tools string constants, representing the tool mode to set

JavaScript

1this._viewer.setToolMode(Config.Tools.annotationCreateFreeHand);

commitTool

Commits the current tool, only available for multi-stroke ink and poly-shape.

Returns a Promise.

Promise Parameters:

NameTypeDescription
committedbooltrue if either ink or poly-shape tool is committed, false otherwise

JavaScript

1this._viewer.commitTool().then((committed) => {
2 // committed: true if either ink or poly-shape tool is committed, false otherwise
3});

Page

getPageCount

Gets the total number of pages in the currently displayed document.

Returns a Promise.

Promise Parameters:

NameTypeDescription
pageCountintthe current page count of the document

JavaScript

1this._viewer.getPageCount().then((pageCount) => {
2 console.log('pageCount', pageCount);
3});

setCurrentPage

Sets current page of the document.

Parameters:

NameTypeDescription
pageNumberintthe page number for the target crop box; 1-indexed

Returns a Promise.

Promise Parameters:

NameTypeDescription
successbooleanwhether the setting process was successful

JavaScript

1this._viewer.setCurrentPage(4).then((success) => {
2 if (success) {
3 console.log("Current page is set to 4.");
4 }
5});

gotoPreviousPage

Go to the previous page of the document. If on first page, it would stay on first page.

Returns a Promise.

Promise Parameters:

NameTypeDescription
successbooleanwhether the setting process was successful (no change due to staying in first page counts as being successful)

JavaScript

1this._viewer.gotoPreviousPage().then((success) => {
2 if (success) {
3 console.log("Go to previous page.");
4 }
5});

gotoNextPage

Go to the next page of the document. If on last page, it would stay on last page.

Returns a Promise.

Promise Parameters:

NameTypeDescription
successbooleanwhether the setting process was successful (no change due to staying in last page counts as being successful)

JavaScript

1this._viewer.gotoNextPage().then((success) => {
2 if (success) {
3 console.log("Go to next page.");
4 }
5});

gotoFirstPage

Go to the first page of the document.

Returns a Promise.

Promise Parameters:

NameTypeDescription
successbooleanwhether the setting process was successful

JavaScript

1this._viewer.gotoFirstPage().then((success) => {
2 if (success) {
3 console.log("Go to first page.");
4 }
5});

gotoLastPage

Go to the last page of the document.

Returns a Promise.

Promise Parameters:

NameTypeDescription
successbooleanwhether the setting process was successful

JavaScript

1this._viewer.gotoLastPage().then((success) => {
2 if (success) {
3 console.log("Go to last page.");
4 }
5});

getPageCropBox

Gets the crop box for specified page as a JSON object.

Parameters:

NameTypeDescription
pageNumberintegerthe page number for the target crop box. It is 1-indexed

Returns a Promise.

Promise Parameters:

NameTypeDescription
cropBoxobjectan object with information about position (x1, y1, x2 and y2) and size (width and height)

JavaScript

1this._viewer.getPageCropBox(1).then((cropBox) => {
2 console.log('bottom-left coordinate:', cropBox.x1, cropBox.y1);
3 console.log('top-right coordinate:', cropBox.x2, cropBox.y2);
4 console.log('width and height:', cropBox.width, cropBox.height);
5});

getVisiblePages

Gets the visible pages in the current viewer as an array.

Returns a Promise.

Promise Parameters:

NameTypeDescription
visiblePagesarraya list of visible pages in the current viewer

JavaScript

1this._viewer.getVisiblePages().then((visiblePages) => {
2 for (const page of visiblePages) {
3 console.log('page', page, 'is visible.')
4 }
5});

getPageRotation

Gets the rotation value of all pages in the current document.

Returns a Promise.

Promise Parameters:

NameTypeDescription
pageRotationnumberthe rotation degree of all pages, one of 0, 90, 180 or 270 (clockwise).

JavaScript

1this._viewer.getPageRotation().then((pageRotation) => {
2 console.log('The current page rotation degree is' + pageRotation);
3});

rotateClockwise

Rotates all pages in the current document in clockwise direction (by 90 degrees).

Returns a Promise.

this._viewer.rotateClockwise();

rotateCounterClockwise

Rotates all pages in the current document in counter-clockwise direction (by 90 degrees).

Returns a Promise.

this._viewer.rotateCounterClockwise();

Import/Export Annotations

importAnnotationCommand

Imports remote annotation command to local document.

Parameters:

NameTypeDescription
xfdfCommandstringthe XFDF command string
initialLoadbooleanwhether this is for initial load; false by default

Returns a Promise.

JavaScript

1const xfdfCommand = 'xfdfCommand <?xml version="1.0" encoding="UTF-8"?><xfdf xmlns="http://ns.adobe.com/xfdf/" xml:space="preserve"><add><circle style="solid" width="5" color="#E44234" opacity="1" creationdate="D:20201218025606Z" flags="print" date="D:20201218025606Z" name="9d0f2d63-a0cc-4f06-b786-58178c4bd2b1" page="0" rect="56.4793,584.496,208.849,739.369" title="PDF" /></add><modify /><delete /><pdf-info import-version="3" version="2" xmlns="http://www.pdftron.com/pdfinfo" /></xfdf>';
2this._viewer.importAnnotationCommand(xfdf);

importAnnotations

Imports XFDF annotation string to the current document.

Parameters:

NameTypeDescription
xfdfstringannotation string in XFDF format for import

Returns a Promise.

JavaScript

1const xfdf = '<?xml version="1.0" encoding="UTF-8"?>\n<xfdf xmlns="http://ns.adobe.com/xfdf/" xml:space="preserve">\n\t<annots>\n\t\t<circle style="solid" width="5" color="#E44234" opacity="1" creationdate="D:20190729202215Z" flags="print" date="D:20190729202215Z" page="0" rect="138.824,653.226,236.28,725.159" title="" /></annots>\n\t<pages>\n\t\t<defmtx matrix="1.333333,0.000000,0.000000,-1.333333,0.000000,1056.000000" />\n\t</pages>\n\t<pdf-info version="2" xmlns="http://www.pdftron.com/pdfinfo" />\n</xfdf>';
2this._viewer.importAnnotations(xfdf);

exportAnnotations

Extracts XFDF from the current document.

Parameters:

NameTypeDescription
optionsobjectkey: annotList, type: array. If specified, annotations with the matching id and pageNumber will be exported; otherwise, all annotations in the current document will be exported.

Returns a Promise.

Promise Parameters:

NameTypeDescription
xfdfstringannotation string in XFDF format

Without options:

JavaScript

1this._viewer.exportAnnotations().then((xfdf) => {
2 console.log('XFDF for all annotations:', xfdf);
3});

With options:

JavaScript

1// annotList is an array of annotation data in the format {id: string, pageNumber: int}
2const annotations = [{id: 'annot1', pageNumber: 1}, {id: 'annot2', pageNumber: 3}];
3this._viewer.exportAnnotations({annotList: annotations}).then((xfdf) => {
4 console.log('XFDF for 2 specified annotations', xfdf);
5});

Annotations

flattenAnnotations

Flattens the forms and (optionally) annotations in the current document.

Parameters:

NameTypeDescription
formsOnlybooleanDefines whether only forms are flattened. If false, all annotations will be flattened

Returns a Promise.

JavaScript

1// flatten forms and annotations in the current document.
2this._viewer.flattenAnnotations(false);

deleteAnnotations

Deletes the specified annotations in the current document.

Parameters:

NameTypeDescription
annotationsarrayDefines which annotations to be deleted. Each element is in the format {id: string, pageNumber: int}

Returns a Promise.

JavaScript

1// delete annotations in the current document.
2this._viewer.deleteAnnotations([
3 {
4 id: 'annotId1',
5 pageNumber: 1,
6 },
7 {
8 id: 'annotId2',
9 pageNumber: 2,
10 }
11]);

selectAnnotation

Selects the specified annotation in the current document.

Parameters:

NameTypeDescription
idstringthe id of the target annotation
pageNumberintegerthe page number where the targe annotation is located. It is 1-indexed

Returns a Promise.

JavaScript

1// select annotation in the current document.
2this._viewer.selectAnnotation('annotId1', 1);

setFlagsForAnnotations

Sets flags for specified annotations in the current document. The flagValue controls whether a flag will be set to or removed from the annotation.

Note: the old function setFlagForAnnotations is deprecated. Please use this one.

Parameters:

NameTypeDescription
annotationFlagListarrayA list of annotation flag operations. Each element is in the format {id: string, pageNumber: int, flag: Config.AnnotationFlags constants, flagValue: bool}

Returns a Promise.

JavaScript

1// Set flag for annotations in the current document.
2this._viewer.setFlagsForAnnotations([
3 {
4 id: 'annotId1',
5 pageNumber: 1,
6 flag: Config.AnnotationFlags.noView,
7 flagValue: true
8 },
9 {
10 id: 'annotId2',
11 pageNumber: 5,
12 flag: Config.AnnotationFlags.lockedContents,
13 flagValue: false
14 }
15]);

setPropertiesForAnnotation

Sets properties for specified annotation in the current document, if it is valid.

Note: the old function setPropertyForAnnotation is deprecated. Please use this one.

Parameters:

NameTypeDescription
annotationIdstringthe unique id of the annotation
pageNumberintegerthe page number where annotation is located. It is 1-indexed
propertyMapobjectan object containing properties to be set. Available properties are listed below

Properties in propertyMap:

NameTypeMarkup exclusiveExample
rectobjectno{x1: 1, y1: 2, x2: 3, y2: 4}
contentsstringno"contents"
subjectstringyes"subject"
titlestringyes"title"
contentRectobjectyes{x1: 1, y1: 2, x2: 3, y2: 4}
customDataobjectno{key: value}
strokeColorobjectno{red: 255, green: 0, blue: 0}

Returns a promise.

JavaScript

1// Set properties for annotation in the current document.
2this._viewer.setPropertiesForAnnotation('Pdftron', 1, {
3 rect: {
4 x1: 1.1, // left
5 y1: 3, // bottom
6 x2: 100.9, // right
7 y2: 99.8 // top
8 },
9 contents: 'Hello World',
10 subject: 'Sample',
11 title: 'set-prop-for-annot',
12 customData: {
13 key1: 'value1',
14 key2: 'value2',
15 key3: 'value3'
16 },
17 strokeColor: {
18 "red": 255,
19 "green": 0,
20 "blue": 0
21 }
22});

getPropertiesForAnnotation

Gets properties for specified annotation in the current document, if it is valid.

Parameters:

NameTypeDescription
annotationIdstringthe unique id of the annotation
pageNumberintegerthe page number where annotation is located. It is 1-indexed

Available Properties:

NameTypeMarkup exclusiveExample
rectobjectno{x1: 1, y1: 2, x2: 3, y2: 4}
contentsstringno"contents"
subjectstringyes"subject"
titlestringyes"title"
contentRectobjectyes{x1: 1, y1: 2, x2: 3, y2: 4}
strokeColorobjectno{red: 255, green: 0, blue: 0}

Returns a promise.

Promise Parameters:

NameTypeDescriptionExample
propertyMapobjectthe non-null properties of the annotation{contents: 'Contents', strokeColor: {red: 255, green: 0, blue: 0}, rect: {x1: 1, y1: 1, x2: 2, y2: 2, width: 1, height: 1}}

JavaScript

1// Get properties for annotation in the current document.
2this._viewer.getPropertiesForAnnotation('Pdftron', 1).then((properties) => {
3 if (properties) {
4 console.log('Properties for annotation: ', properties);
5 }
6})

setDrawAnnotations

Sets whether all annotations and forms should be rendered in the viewer.

Parameters:

NameTypeDescription
drawAnnotationsbooleanwhether all annotations and forms should be rendered

Returns a promise.

this._viewer.setDrawAnnotations(false);

setVisibilityForAnnotation

Sets visibility for specified annotation in the current document, if it is valid. Note that if drawAnnotations is set to false in the viewer, this function would not render the annotation even if visibility is true.

Parameters:

NameTypeDescription
annotationIdstringthe unique id of the annotation
pageNumberintegerthe page number where annotation is located. It is 1-indexed
visibilityboolwhether the annotation should be visible

Returns a promise.

this._viewer.setVisibilityForAnnotation('Pdftron', 1, true);

setHighlightFields

Enables or disables highlighting form fields. It is disabled by default.

Parameters:

NameTypeDescription
highlightFieldsboolwhether form fields should be highlighted

this._viewer.setHighlightFields(true);

getAnnotationAt

Gets an annotation at the (x, y) position in screen coordinates, if any.

Parameters:

NameTypeDescription
xintthe x-coordinate of the point
yintthe y-coordinate of the point
distanceThresholddoublemaximum distance from the point (x, y) to the annotation for it to be considered a hit (in dp)
minimumLineWeightdoubleFor very thin lines, it is almost impossible to hit the actual line. This specifies a minimum line thickness (in screen coordinates) for the purpose of calculating whether a point is inside the annotation or not (in dp)

Returns a Promise.

Promise Parameters:

NameTypeDescription
annotationobjectthe annotation found in the format of {id: string, pageNumber: number, type: string, rect: {x1: number, y1: number, x2: number, y2: number}}

JavaScript

1this._viewer.getAnnotationAt(167, 287, 100, 10).then((annotation) => {
2 if (annotation) {
3 console.log('Annotation found at point (167, 287) has id:', annotation.id);
4 }
5})

getAnnotationListAt

Gets the list of annotations at a given line in screen coordinates. Note that this is not an area selection. It should be used similar to getAnnotationAt, except that this should be used when you want to get multiple annotations which are overlaying with each other.

Parameters:

NameTypeDescription
x1intthe x-coordinate of an endpoint on the line
y1intthe y-coordinate of an endpoint on the line
x2intthe x-coordinate of the other endpoint on the line, usually used as a threshold
y2intthe y-coordinate of the other endpoint on the line, usually used as a threshold

Returns a Promise.

Promise Parameters:

NameTypeDescription
annotationarraylist of annotations at the target line, each in the format of {id: string, pageNumber: number, type: string, rect: {x1: number, y1: number, x2: number, y2: number}}

JavaScript

1this._viewer.getAnnotationListAt(0, 0, 200, 200).then((annotations) => {
2 for (const annotation of annotations) {
3 console.log('Annotation found at line has id:', annotation.id);
4 }
5})

getAnnotationListOnPage

Gets the list of annotations on a given page.

Parameters:

NameTypeDescription
pageNumberintegerthe page number where annotations are located. It is 1-indexed

Returns a Promise.

Promise Parameters:

NameTypeDescription
annotationsarraylist of annotations on the target page, each in the format of {id: string, pageNumber: number, type: string, rect: {x1: number, y1: number, x2: number, y2: number}}

JavaScript

1this._viewer.getAnnotationListOnPage(2).then((annotations) => {
2 for (const annotation of annotations) {
3 console.log('Annotation found on page 2 has id:', annotation.id);
4 }
5})

getCustomDataForAnnotation

Gets an annotation's customData property.

Parameters:

NameTypeDescription
annotationIdstringthe unique id of the annotation
pageNumberintegerthe page number where annotation is located. It is 1-indexed
keystringthe unique key associated with the customData property

Returns a Promise.

Promise Parameters:

NameTypeDescription
valuestringthe customData property associated with the given key

JavaScript

1this._viewer.setPropertiesForAnnotation("annotation1", 2, {
2 customData: {
3 data: "Nice annotation"
4 }
5}).then(() => {
6 this._viewer.getCustomDataForAnnotation("annotation1", 2, "data").then((value) => {
7 console.log(value === "Nice annotation");
8 })
9})

setFlagForFields

Sets a field flag value on one or more form fields.

Parameters:

NameTypeDescription
fieldsarraylist of field names for which the flag should be set
flagintflag to be set. Number should be a Config.FieldFlags constant
valueboolvalue to set for flag

Returns a Promise.

JavaScript

1this._viewer.setFlagForFields(['First Name', 'Last Name'], Config.FieldFlags.ReadOnly, true);

setValuesForFields

Sets field values on one or more form fields.

Note: the old function setValueForFields is deprecated. Please use this one instead.

Parameters:

NameTypeDescription
fieldsMapobjectmap of field names and values which should be set

Returns a Promise.

JavaScript

1this._viewer.setValuesForFields({
2 'textField1': 'Test',
3 'textField2': 1234,
4 'checkboxField1': true,
5 'checkboxField2': false,
6 'radioButton1': 'Yes',
7 'radioButton2': 'No'
8});

getField

Get type and value information of a field using its name.

Parameters:

NameTypeDescription
fieldNamestringname of the field

Returns a Promise.

Promise Parameters:

NameTypeDescription
fieldobjectan object with information key fieldName, fieldValue (undefined for fields with no values) and fieldType(one of button, checkbox, radio, text, choice, signature and unknown), or undefined if such field does not exist

JavaScript

1this._viewer.getField('someFieldName').then((field) => {
2 if (field !== undefined) {
3 console.log('field name:', field.fieldName);
4 console.log('field value:', field.fieldValue);
5 console.log('field type:', field.fieldType);
6 }
7});

handleBackButton

Handles the back button in search mode. Android only.

Returns a Promise.

Promise Parameters:

NameTypeDescription
handledboolwhether the back button is handled successfully

JavaScript

1this._viewer.handleBackButton().then((handled) => {
2 if (!handled) {
3 BackHandler.exitApp();
4 }
5});

Bookmark

importBookmarkJson

Imports user bookmarks into the document. The input needs to be a valid bookmark JSON format.

Parameters:

NameTypeDescription
bookmarkJsonStringneeds to be in valid bookmark JSON format, for example {"0": "Page 1"}. The page numbers are 1-indexed

Returns a Promise.

JavaScript

1this._viewer.importBookmarkJson("{\"0\": \"Page 1\", \"3\": \"Page 4\"}");

Multi-tab

closeAllTabs

Closes all tabs in multi-tab environment.

Returns a Promise.

JavaScript

1// Do this only when DocumentView has multiTabEnabled = true
2this._viewer.closeAllTabs();

Zoom

getZoom

Returns the current zoom scale of current document viewer.

Returns a Promise.

Promise Parameters:

NameTypeDescription
zoomdoublecurrent zoom scale in the viewer

JavaScript

1this._viewer.getZoom().then((zoom) => {
2 console.log('Zoom scale of the current document is:', zoom);
3});

setZoomLimits

Sets the minimum and maximum zoom bounds of current viewer.

Parameters:

NameTypeDescription
zoomLimitModeStringone of the constants in Config.ZoomLimitMode, defines whether bounds are relative to the standard zoom scale in the current viewer or absolute
minimumdoublethe lower bound of the zoom limit range
maximumdoublethe upper bound of the zoom limit range

Returns a Promise.

JavaScript

1this._viewer.setZoomLimits(Config.ZoomLimitMode.Absolute, 1.0, 3.5);

zoomWithCenter

Sets the zoom scale in the current document viewer with a zoom center.

Parameters:

NameTypeDescription
zoomdoublethe zoom ratio to be set
xintthe x-coordinate of the zoom center
yintthe y-coordinate of the zoom center

Returns a Promise.

JavaScript

1this._viewer.zoomWithCenter(3.0, 100, 300);

zoomToRect

Zoom the viewer to a specific rectangular area in a page.

Parameters:

NameTypeDescription
pageNumberintthe page number of the zooming area (1-indexed)
rectmapThe rectangular area with keys x1 (left), y1(bottom), y1(right), y2(top). Coordinates are in double

Returns a Promise.

JavaScript

1this._viewer.zoomToRect(3, {'x1': 1.0, 'y1': 2.0, 'x2': 3.0, 'y2': 4.0});

smartZoom

Zoom to a paragraph that contains the specified coordinate. If no paragraph contains the coordinate, the zooming would not happen.

Parameters:

NameTypeDescription
xintthe x-coordinate of the target coordinate
yintthe y-coordinate of the zoom center
animatedboolwhether the transition is animated

Returns a Promise.

this._viewer.smartZoom(100, 200, true);

Scroll

getScrollPos

Returns the horizontal and vertical scroll position of current document viewer.

Returns a Promise.

Promise Parameters:

NameTypeDescription
horizontalnumbercurrent horizontal scroll position
verticalnumbercurrent vertical scroll position

JavaScript

1this._viewer.getScrollPos().then(({horizontal, vertical}) => {
2 console.log('Current horizontal scroll position is:', horizontal);
3 console.log('Current vertical scroll position is:', vertical);
4});

Canvas

getCanvasSize

Returns the canvas size of current document viewer.

Returns a Promise.

Promise Parameters:

NameTypeDescription
widthnumbercurrent width of canvas
heightnumbercurrent height of canvas

JavaScript

1this._viewer.getCanvasSize().then(({width, height}) => {
2 console.log('Current canvas width is:', width);
3 console.log('Current canvas height is:', height);
4});

Coordinate

convertPagePointsToScreenPoints

Converts points from page coordinates to screen coordinates in the viewer.

Parameters:

NameTypeDescription
pointsarraylist of points, each in the format {x: number, y: number}. You could optionally have a pageNumber: number in the object. Without specifying, the page system is referring to the current page

Returns a Promise.

Promise Parameters:

NameTypeDescription
convertedPointsarraylist of converted points in screen system, each in the format {x: number, y: number}. It would be empty if conversion is unsuccessful

JavaScript

1// convert (50, 50) on current page and (100, 100) on page 1 from page system to screen system
2this._viewer.convertPagePointsToScreenPoints([{x: 50, y: 50}, {x: 100, y:100, pageNumber: 1}]).then((convertedPoints) => {
3 convertedPoints.forEach(point => {
4 console.log(point);
5 })
6});

convertScreenPointsToPagePoints

Converts points from screen coordinates to page coordinates in the viewer.

Parameters:

NameTypeDescription
pointsarraylist of points, each in the format {x: number, y: number}. You could optionally have a pageNumber: number in the object. Without specifying, the page system is referring to the current page

Returns a Promise.

Promise Parameters:

NameTypeDescription
convertedPointsarraylist of converted points in page system, each in the format {x: number, y: number}. It would be empty if conversion is unsuccessful

JavaScript

1// convert (50, 50) and (100, 100) from screen system to page system, on current page and page 1 respectively
2this._viewer.convertScreenPointsToPagePoints([{x: 50, y: 50}, {x: 100, y:100, pageNumber: 1}]).then((convertedPoints) => {
3 convertedPoints.forEach(point => {
4 console.log(point);
5 })
6});

getPageNumberFromScreenPoint

Returns the page number that contains the point on screen.

Parameters:

NameTypeDescription
xnumberthe x-coordinate of the screen point
ynumberthe y-coordinate of the screen point

Returns a Promise.

Promise Parameters:

NameTypeDescription
pageNumbernumberthe page number of the screen point

JavaScript

1this._viewer.getPageNumberFromScreenPoint(10.0,50.5).then((pageNumber) => {
2 console.log('The page number of the screen point is', pageNumber);
3});

Rendering Options

setProgressiveRendering

Sets whether the control will render progressively or will just draw once the entire view has been rendered.

Parameters:

NameTypeDescription
progressiveRenderingboolwhether to render progressively
initialDelaynumberdelay before the progressive rendering timer is started, in milliseconds
intervalnumberdelay between refreshes, in milliseconds

Returns a Promise.

JavaScript

1// delay for 10s before start, and refresh every 1s
2this._viewer.setProgressiveRendering(true, 10000, 1000);

setImageSmoothing

Enables or disables image smoothing. The rasterizer allows a trade-off between rendering quality and rendering speed. This function can be used to indicate the preference between rendering speed and quality.

Parameters:

NameTypeDescription
imageSmoothingboolbool whether to enable image smoothing

Returns a Promise.

JavaScript

1this._viewer.setImageSmoothing(false);

setOverprint

Enables or disables support for overprint and overprint simulation. Overprint is a device dependent feature and the results will vary depending on the output color space and supported colorants (i.e. CMYK, CMYK+spot, RGB, etc).

Parameters:

NameTypeDescription
overprintoverprintthe mode of overprint, should be a Config.OverprintMode constant

Returns a Promise.

this._viewer.setOverprint(Config.OverprintMode.Off);

Viewer Options

setUrlExtraction

Sets whether to extract urls from the current document, which is disabled by default. It is recommended to set this value before document is opened.

Parameters:

NameTypeDescription
urlExtractionboolwhether to extract urls from the current document

this._viewer.setUrlExtraction(true);

setPageBorderVisibility

Sets whether borders of each page are visible in the viewer, which is disabled by default.

Parameters:

NameTypeDescription
pageBorderVisibilityboolwhether borders of each page are visible in the viewer

this._viewer.setPageBorderVisibility(true);

setPageTransparencyGrid

Enables or disables transparency grid (check board pattern) to reflect page transparency, which is disabled by default.

Parameters:

NameTypeDescription
pageTransparencyGridboolwhether to use the transpareny grid

this._viewer.setPageTransparencyGrid(true);

setBackgroundColor

Sets the background color of the viewer.

Parameters:

NameTypeDescription
backgroundColorobjectthe background color, in the format {red: number, green: number, blue: number}, each number in range [0, 255]

this._viewer.setBackgroundColor({red: 0, green: 0, blue: 255}); // blue color

setDefaultPageColor

Sets the default page color of the viewer.

Parameters:

NameTypeDescription
defaultPageColorobjectthe default page color, in the format {red: number, green: number, blue: number}, each number in range [0, 255]

this._viewer.setDefaultPageColor({red: 0, green: 255, blue: 0}); // green color

Text Selection

findText

Searches asynchronously, starting from the current page, for the given text. PDFViewCtrl automatically scrolls to the position so that the found text is visible.

Returns a Promise.

Promise Parameters:

NameTypeDescription
searchStringstringthe text to search for
matchCaseboolindicates if it is case sensitive
matchWholeWordboolindicates if it matches an entire word only
searchUpboolindicates if it searches upward
regExpboolindicates if searchString is a regular expression

this._viewer.findText('Apryse', false, false, true, false);

cancelFindText

Cancels the current text search thread, if exists.

Returns a Promise.

this._viewer.cancelFindText();

getSelection

Returns the text selection on a given page, if any.

Returns a Promise.

Promise Parameters:

NameTypeDescription
selectionobjectthe text selection, in the format {html: string, unicode: string, pageNumber: number, quads: [[{x: number, y: number}, {x: number, y: number}, {x: number, y: number}, {x: number, y: number}], ...]}. If no such selection could be found, this would be null

quads indicate the quad boundary boxes for the selection, which could have a size larger than 1 if selection spans across different lines. Each quad have 4 points with x, y coordinates specified in number, representing a boundary box. The 4 points are in counter-clockwise order, though the first point is not guaranteed to be on lower-left relatively to the box.

JavaScript

1this._viewer.getSelection(2).then((selection) => {
2 if (selection) {
3 console.log('Found selection on page', selection.pageNumber);
4 for (let i = 0; i < selection.quads.length; i ++) {
5 const quad = selection.quads[i];
6 console.log('selection boundary quad', i);
7 for (const quadPoint of quad) {
8 console.log('A quad point has coordinates', quadPoint.x, quadPoint.y);
9 }
10 }
11 }
12});

hasSelection

Returns whether there is a text selection in the current document.

Returns a Promise.

Promise Parameters:

NameTypeDescription
hasSelectionboolwhether a text selection exists

JavaScript

1this._viewer.hasSelection().then((hasSelection) => {
2 console.log('There is a selection in the document.');
3});

clearSelection

Clears any text selection in the current document.

Returns a Promise.

this._viewer.clearSelection();

getPageSelectionRange

Returns the page range (beginning and end) that has text selection on it.

Returns a Promise.

Promise Parameters:

NameTypeDescription
beginnumberthe first page to have selection, -1 if there are no selections
endnumberthe last page to have selection, -1 if there are no selections

JavaScript

1this._viewer.getPageSelectionRange().then(({begin, end}) => {
2 if (begin === -1) {
3 console.log('There is no selection');
4 } else {
5 console.log('The selection range is from', begin, 'to', end);
6 }
7});

hasSelectionOnPage

Returns whether there is a text selection on the specified page in the current document.

Parameters:

NameTypeDescription
pageNumbernumberthe specified page number. It is 1-indexed

Returns a Promise.

Promise Parameters:

NameTypeDescription
hasSelectionboolwhether a text selection exists on the specified page

JavaScript

1this._viewer.hasSelectionOnPage(5).then((hasSelection) => {
2 if (hasSelection) {
3 console.log('There is a selection on page 5 in the document.');
4 }
5});

selectInRect

Selects the text within the given rectangle region.

Parameters:

NameTypeDescription
rectobjectthe rectangle region in the format of x1: number, x2: number, y1: number, y2: number

Returns a Promise.

Promise Parameters:

NameTypeDescription
selectedboolwhether there is text selected

JavaScript

1this._viewer.selectInRect({x1: 0, y1: 0, x2: 200.5, y2: 200.5}).then((selected) => {
2 console.log(selected);
3});

isThereTextInRect

Returns whether there is text in given rectangle region.

Parameters:

NameTypeDescription
rectobjectthe rectangle region in the format of x1: number, x2: number, y1: number, y2: number

Returns a Promise.

Promise Parameters:

NameTypeDescription
hasTextboolwhether there is text in the region

JavaScript

1this._viewer.isThereTextInRect({x1: 0, y1: 0, x2: 200, y2: 200}).then((hasText) => {
2 console.log(hasText);
3});

selectAll

Selects all text on the page.

Returns a Promise.

this._viewer.selectAll();

exportAsImage

Export a PDF page to image format defined in Config.ExportFormat.

Parameters:

NameTypeDescription
pageNumberintthe page to be converted
dpidoublethe output image resolution
exportFormatstringone of Config.ExportFormat

Returns a Promise.

NameTypeDescription
pathstringthe temp path of the created image, user is responsible for clean up the cache

JavaScript

1this._viewer.exportToImage(1, 92, Config.ExportFormat.BMP).then((path) => {
2 console.log('export', path);
3});

undo

Undo the last modification.

Returns a Promise.

this._viewer.undo();

redo

Redo the last modification.

Returns a Promise.

this._viewer.redo();

showCrop

Displays the page crop option. Android only.

Returns a Promise.

this._viewer.showCrop();

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales