Documents for PDF .NET Edition
GrapeCity Documents PDF Viewer / GrapeCity Documents PDF Viewer API
In This Topic
    GrapeCity Documents PDF Viewer API
    In This Topic

    Options

    The following options can be set during initialization or at run time while working with GcDocs PDF Viewer.

    Options Descriptions Types Example
    baseUrl

    Used by form submission and for theme urls.

    undefined | string

    var viewer = new GcPdfViewer("#root", { baseUrl: "http://localhost/mysite/" });

    caret Shows caret for selection. This option is available only when useCanvasForSelection option is set to true. object

    viewer.options.caret =
    {/**
    * milliseconds, caret blink period
    * */
    caretBlinkTime: 300,
    /**
    * milliseconds, stop caret blink time, 0 - don't stop
    * */
    caretStopBlinkTime: 5000,
    /**
    * Caret color
    * */
    color: "#000000",
    /**
    * Caret width
    * */
    width: 1,
    /**
    * Allow to move caret using keys even when pan tool activated.
    * */
    allowForPan: false };

    disablePageLabels Set this options to true if you wish to disable page labels. Default value is false. undefined | false | true var viewer = new GcPdfViewer("#root", { disablePageLabels: true } );
    externalLinkTarget

    The externalLinkTarget option sets the value of the target attribute of a link annotation.The externalLinkTarget option specifies where to open the linked document.

    Possible values: 'blank', 'self', 'parent', 'top', 'none', default is 'none'. 

    "blank" | "self" | "parent" | "top" | "none" var viewer = new GcPdfViewer("#root", { externalLinkTarget: "self" } );
    useCanvasForSelection If this option is set to false, then static forms are rendered. If the option is set to true, then interactive form elements are rendered. object viewer.options.useCanvasForSelection =
    {selectionColor: "rgba(145, 44, 39, 0.2)",
    highlightColor: "rgba(83, 145, 39, 1)",
    inactiveHighlightColor: "rgba(180, 0, 170, 0.35)"};
    renderInteractiveForms To render static forms, set this option to false and to render interactive form elements, set this option to true.  boolean  // Do not render interactive form:
    var viewer = new GcPdfViewer("#root", { renderInteractiveForms: false } );
    keepFileData

    Set this option to true if you want to use fileData property even when the document cannot be parsed as a valid PDF document.

    boolean // Below is an example of how to display invalid file data when an error occurs:
    var viewer = new GcPdfViewer('#root', { keepFileData: true });
    viewer.onError.register(function(eventArgs) {
      var message = eventArgs.message;
      if (message.indexOf("Invalid PDF structure") !== -1) {
        console.log('Unable to load pdf document, pdf document is broken.');
        console.log("File data:");
        // Output file data to console:
        console.log(viewer.fileData);
      } else {
        console.log('Unexpected error: ' + message);
      }
    });
    viewer.open('sample.pdf');
    renderer

    Specify the renderer type; canvas or svg. Default value is set to canvas. 

    "canvas" | "svg" var viewer = new GcPdfViewer("#root", { renderer: "svg" } );
    friendlyFileName Sets an alternative file name to be displayed in the title field of the Viewer while saving the PDF document. undefined | string viewer.options.friendlyFileName = "myFileName.pdf";
    viewer.applyOptions();
    file Specifies the PDF file name, URL, or binary data to be loaded in the Viewer.  undefined | string viewer.options.file =  'GcPdf.pdf';
    password

    Sets the predefined password for a protected PDF document. This option is useful when you do not wish to enter password in the Viewer. 

    string viewer.options.password = "1";
    viewer.open("protected.pdf");
    workerSrc

    URL to the Web Worker script. The Web Worker script runs in the background and is used to load and render PDF documents in a parallel background thread. Please, note, that rendering a PDF on the main thread (without a Web Worker script) can slow down the performance of the PDF viewer when loading large PDF files.

    string  var viewer = new GcPdfViewer("#root", { workerSrc: "http://localhost:5000/gcpdfviewer.worker.js" } );
    themes Specifies the available themes for Viewer.  string 

    viewer.options.themes =  ["themes/viewer", "themes/light-blue", "themes/dark-yellow"];

    zoomByMouseWheel Sets the options available for zooming the PDF document using mouse wheel.  object 

    viewer.options.zoomByMouseWheel =
    { always: false, ctrlKey: false, metaKey: true };

    shortcut

    Sets keyboard shortcuts.
     
     

     

    object

    viewer.options.shortcuts =
    {
    107: {// + (numpad)
    ctrl: true,
    tool: "zoomin"      
    },
    "S": {
          tool: "selection"
     },

    theme

    Modifies the default theme for Viewer.

    List of supported themes: viewer, light-blue and dark-yellow.

    string viewer.options.theme = "dark-yellow.css";
    restoreViewStateOnLoad

    Tracks view changes and restores the previous state on the next page load.

    Available values: false true, { trackViewMode: boolean, trackMouseMode: boolean, trackScale: boolean, trackPageRotation: boolean, trackFullScreen: boolean, trackTheme: boolean }

    object

    // enable all
    viewer.options .restoreViewStateOnLoad = true;
    // disable view changes tracking
    viewer.options .restoreViewStateOnLoad = false
    // enable only scale tracking
    viewer.options.restoreViewStateOnLoad =  {trackScale: true}
    var viewer = new GcPdfViewer("#root", { restoreViewStateOnLoad: { trackScale: true } });
    viewer.addDefaultPanels();

    documentListUrl

    URL to document list service used by DocumentListPanel.

    Default value is "/documents". For more information, see addDocumentListPanel method. The service should return json string with available documents array, e.g.:
    ["pdf1.pdf", "pdf2.pdf"] 

     

    string

    // Using GetDocumentsList service method to get array of the available PDF documents
    var viewer = new GcPdfViewer(“#root”, { documentListUrl: "/GetDocumentsList" } );
    viewer.addDocumentListPanel();

    You can even replace «GetDocumentsList» API by json file
    (see example from addDocumentListPanel method description)

    cMapPacked

    Indicates if the viewer should look for a compressed version of the CMap file with the extension '.bin', default value is true.

     

    undefined | false | true var viewer = new GcPdfViewer("#root", { cMapPacked: false } );
    cMapUrl

    The URI to a folder where the external font CMap tables are stored, default value is 'resources/bcmaps/'

     

    undefined | string var viewer = new GcPdfViewer("#root", { cMapUrl: "../data/cmaps/" } );
    coordinatesOrigin

    Origin coordinates for the PDF page. The option is used for a properties panel of the Annotation and Form Editor.

    "TopLeft" | "BottomLeft"

    // Change the coordinates origin to bottom/left point:
    var viewer = new GcPdfViewer("#root", { coordinatesOrigin: "BottomLeft" } );

    hideAnnotationTypes

    Specifies annotation types which will be hidden when 'hide-annotations' button is checked. Possible values are: ['Text',  'Link',  'FreeText',  'Line',  'Square',  'Circle',  'Polygon', 'Polyline',  'Ink',  'Popup',  'FileAttachment', 'Sound',  'ThreadBead',  'RadioButton',  'Checkbox', 'PushButton',  'Choice', 'TextWidget',  'Redact'] or 'All' or 'None'

     

    "Text" | "Link" | "FreeText" | "Line" | "Square" | "Circle" | "Polygon" | "Ink" | "Popup" | "FileAttachment" | "Sound" | "Redact" | "Signature" | "ThreadBead" | "RadioButton" | "Checkbox" | "PushButton" | "Choice" | "TextWidget" | "Polyline")[] | "All" | "None"

    // Hide all possible annotations.
    let options = { hideAnnotationTypes: 'All' };


    // Hide Push button and Redact annotations only.
    let options = { hideAnnotationTypes: ['PushButton', 'Redact'] };

    language

    User interface language.

     

    "en" | string

    function loadPdfViewer(selector) {
      // You can load translations from any source (see en-pdf-viewer.json for an example):
      var myTranslations = {
            "toolbar": {
                "open-document": "Open MY document",
                "pan": "My Pan tool",
            }
       };
       // Initialize translations:
       GcPdfViewer.i18n.init({
         resources: { myLang: { translation: myTranslations } }
       }).then(function(t) {
         // New translations initialized and ready to go!
         // Now create PDF viewer:
         var viewer = new GcPdfViewer(selector, { language: 'myLang' });
         viewer.addDefaultPanels();
         //viewer.open("sample.pdf");
       });
    }
    loadPdfViewer('#root');

    onBeforeCloseContextMenu

    This function will be called when context menu is about to be hidden. Return false if you want to prevent close context menu action.

     

    Function

    viewer.options.onBeforeCloseContextMenu = function(e) {
      console.log("The context menu will be closed soon.");
      return true;
    };


    viewer.options.onBeforeCloseContextMenu = function(e) {
      if(!confirm("Do you want to close context menu?")) {
          console.log("The context menu will not be closed.");
          return false;
      }
      console.log("The context menu will be closed.");
      return true;
    };

    onBeforeOpenContextMenu

    This function will be called when context menu is about to be shown. You can use this function to customize context menu. Return false if you want to prevent open context menu action.

     

    Function

    // This code shows how to modify the context menu and
     // add search using Google and Bing search engines:
     viewer.options.onBeforeOpenContextMenu = function (items, mousePosition, viewer) {
      var selectedText = viewer.getSelectedText();
      if (selectedText) {
        // Remove existent items:
        items.splice(0, items.length);
        // Add own menu items:
        items.push({
           type: 'button',
           text: 'Search using Google',
           onClick: function () {
                 window.open('http://www.google.com/search?q=' + encodeURI(selectedText), '_blank');
           }
        });
        items.push({
           type: 'button',
           text: 'Search using Bing',
           onClick: function () {
               window.open('https://www.bing.com/search?q=' + encodeURI(selectedText), '_blank');
          }
        });
       }
       return true;
     };

    snapAlignment

    The Snap Alignment feature customization settings.The tolerance setting is the distance between the edges of two objects within which the object that is being
    moved or resized snaps to the other object. Margin is the extra space before or after the edge of a field or page. The margin setting is the distance from the target object to which the edge of the object being moved or resized snaps. The center setting allows to snap objects to centers of other objects (in addition to edges).

     

    true | false | { center: false | true | { horizontal: boolean; vertical: boolean }; margin: false | true | number | { horizontal: number | boolean; vertical: number | boolean }; tolerance: number | { horizontal: number | false; vertical: number | false } }

    // Enable vertical snap margin:
    var viewer = new GcPdfViewer("#root", { snapAlignment: { margin: { vertical: 10, horizontal: false} }, supportApi: 'api/pdf-viewer'});

    supportApi

    URL to an external Web API service which will be used to enable PDF editing features.

     

    string | { apiUrl: string; docBaseUrl: string; suppressErrorMessages?: undefined | false | true; suppressInfoMessages?: undefined | false | true }

    var viewer = new GcPdfViewer("#host",

    { supportApi: 'api/pdf-viewer' }
    );

    useNativeContextMenu

    By default, the viewer uses its own context menu. Set this option to true if you want to use the browser context menu. Please, note, if you set this option to true, some functions of the context menu will not be available (for example, actions of the Editor and Reply tool).

     

    boolean

    // Enable native browser context menu:
    var viewer = new GcPdfViewer("#root", { useNativeContextMenu: true } );

    userData

    Arbitrary data associated with the viewer. This data is sent to the server when the document is saved.

     

    undefined | false | true

    var viewer = new GcPdfViewer('#root', { supportApi: 'api/pdf-viewer' } );
    viewer.options.userData = { secretNumber: 5, innerData: { innerContent: 'content' } };
    viewer.applyOptions();
    viewer.open('sample.pdf');

    userName

    Author's user name. The option is used by Annotation Editor as default value for 'author' field.

     

    undefined | string

    var viewer = new GcPdfViewer('#root', { userName: 'John', supportApi: 'api/pdf-viewer' });

    Methods

    Method Description Parameters Return Value Example
    addDefaultPanels() Adds default set of sidebar panels in the following order: 'Thumbnails', 'Search', 'Outline', 'Attachments', 'Articles' none void viewer.addDefaultPanels();
    addDocumentListPanel()

    Adds document list panel to the Viewer with available document array specified in documentslist.json file (URL specified by documentListUrl option), located in the root directory of your application.

    Example content for the documentslist.json file:
    [“file1.pdf”, “file2.pdf”].

    Another way is to specify service at the end point for documentListUrl option. The service should return json string with available documents array, e.g.: ["pdf1.pdf", "pdf2.pdf"]

    none void var viewer = new GcPdfViewer(“#root”, { documentListUrl: "/documentslist.json" });
    viewer.addDocumentListPanel();
    addThumbnailsPanel() Adds Thumbnail panel to the Viewer. none void viewer.addThumbnailsPanel();
    addOutlinePanel() Adds Outline panel to the Viewer. none void viewer.addOutlinePanel();
    addArticlesPanel() Adds Articles panel to the Viewer. none void viewer.addArticlesPanel();
    addAttachmentsPanel() Adds Attachment panel to the Viewer. none void viewer.addAttachmentsPanel();
    open() 
    Opens PDF document. 
    file: any URI to PDF document(string) or binary data(Uint8Array).
    Promise

    viewer.open("Documents/HelloWorld.pdf");

    openLocalFile() Opens open local file dialog.  none void viewer.openLocalFile();
    print() Prints the currently displayed PDF document.  none void viewer.print();
    save() Downloads the PDF document loaded in the Viewer to the local disk. file name (optional) Promise viewer.save('Test.pdf');
    goBack() Navigate to the previous page in the document.  none void viewer.goBack();
    goForward() Navigate to the next page in the document. none void viewer.goForward();
    setTheme()

    Set a theme of your choice.

    List of supported themes: viewer, light-blue, dark-yellow. 

    theme name – Name of the theme as specified in themes option. void viewer.setTheme(“themes/dark-yellow”);
    enablePdfToolButtons() Allows you to enable PDF specific toolbar buttons according to your requirements. Note that you don’t need to call this method if you are using buttons option. 

    buttons: string[] | "all" | 'none' = 'all', Available values are:
    ['open', '$navigation', '$split', 'text-selection', 'pan', '$zoom', '$fullscreen', 'rotate', 'view-mode', 'theme-change', 'print', 'save', 'doc-title'] 'all' 'none'

    void viewer.enablePdfToolButtons(['single-page']);
    applyOptions() Enables you to populate changed options.  none void var viewer = new GcPdfViewer(selector);
    viewer.options.buttons = ['print', 'rotate'];
    viewer.applyOptions();
    addAnnotation  Add annotation to document. pageIndex: number
    annotation: AnnotationBase
    Promise // Below is the sample how to copy field with name "field1" and put it to the second page programmatically:
    // Find field widget with name field1:
    var resultData = await viewer.findAnnotation("field1", {findField: 'fieldName'});
    // Clone field:
    var clonedField = viewer.cloneAnnotation(resultData[0].annotation);
    // Change field name property:
    clonedField.fieldName = "field1Copy";
    // Add cloned field to the second page.
    viewer.addAnnotation(1, clonedField);
    addAnnotationEditorPanel Add annotation editor panel. none void viewer.addAnnotationEditorPanel();
    addFormEditorPanel Add form editor panel. none void
    addReplyTool

    Enable the Text Annotation Reply Tool.

    Note, in order to enable ability to edit/remove or add existing replies you need to configure SupportApi, otherwise the Reply Tool will be in read-only mode.

    Default value sidebarState: GcRightSidebarState = "collapsed" pass 'expanded' value if you wish the Reply tool to be expanded initially. Default value is collapsed. void viewer.addReplyTool('expanded');
    addSearchPanel Add Search panel. none void viewer.addSearchPanel();
    addStickyNote

    Add sticky note to the document.

    position: GcSelectionPoint page relative point. Origin is top/left.
     Note, pageIndex must be specified, e.g. viewer.addStickyNote({x: 50,y: 50, pageIndex: 0}).
    void viewer.addStickyNote(viewer.toViewPortPoint({x: 50, y: 50, pageIndex: 0}));
    applyToolbarLayout Call this method in order to apply changes in toolbar layout.

    none

    void viewer.toolbarLayout.viewer.default = ["open", "save"];
    viewer.applyToolbarLayout();
    beginUpdate Suspends notifications until the next call to @see: endUpdate. none void viewer.beginUpdate();
    changeBoundsOrigin This method changes coordinate system origin for rectangle given by parameter bounds and returns converted rectangle value. "pageIndex: number Page index (Zero based).
    bounds: number[] bounds array: [x1, y1, x2, y2]
    srcOrigin: ""TopLeft"" | ""BottomLeft"" Source coordinate system origin. Possible values are: 'TopLeft' or 'BottomLeft'.
    destOrigin: ""TopLeft"" | ""BottomLeft"" Destination coordinate system origin. Possible values are: 'TopLeft' or 'BottomLeft'."
    number var pageIndex = 0;
    var topLeftBounds = [0, 0, 200, 40];
    // Convert the topLeftBounds from TopLeft origin to BottomLeft origin
    // taking into account the viewport from the first page and store
    // the result in the bottomLeftBounds variable:
    var bottomLeftBounds = viewer.changeBoundsOrigin(pageIndex, topLeftBounds, 'TopLeft', 'BottomLeft');
    cloneAnnotation Clone annotation or field given by parameter annotation. annotation: AnnotationBase Annotation to clone. AnnotationBase // Below is the sample how to copy field with name "field1" and put it to the second page programmatically:
    // Find field widget with name field1:
    var resultData = await viewer.findAnnotation("field1", {findField: 'fieldName'});
    // Clone field:
    var clonedField = viewer.cloneAnnotation(resultData[0].annotation);
    // Change field name property:
    clonedField.fieldName = "field1Copy";
    // Add cloned field to the second page.
    viewer.addAnnotation(1, clonedField);
    deletePage Delete page. pageIndex: undefined | number Optional, page index to delete. void // Delete page with index 3.
    viewer.deletePage(3);
    download Download current PDF document to local disk. fileName: undefined | string Optional, destination file name. void viewer.download();
    endUpdate Resumes notifications suspended by calls to @see:beginUpdate. none void viewer.endUpdate();
    execCopyAction

    Execute Copy action (Ctrl + C shortcut).

    buffer: CopyBufferData Optional, data to copy. Promise viewer.execCopyAction();
    execCutAction Execute Cut action (Ctrl + X shortcut). 

    buffer: CopyBufferData Optional, data to cut.

    Promise viewer.execCutAction();
    execDeleteAction Execute Delete action (DEL shortcut). buffer: CopyBufferData Optional, data to delete. Promise viewer.execDeleteAction();
    execPasteAction Execute Paste action (Ctrl + V shortcut). point: GcSelectionPoint Optional, insert position. Promise if(viewer.hasCopyData) {
      viewer.execPasteAction({x: 10, y: 10, pageIndex: 0});
    }
    findAnnotation Find annotation(s) within opened document. Returns promise which will be resolved with search results. findString: string Find query.
    findParams: undefined | { findAll?: undefined | false | true; findField?: ""id"" | ""title"" | ""contents"" | ""fieldName"" | string; pageNumberConstraint?: undefined | number } Optional, find parameters. By default annotation will be searched by id without page constraint.
    Promise

    "// Find annotation with id '2R':
    viewer.findAnnotation(""2R"").then(function(dataArray) {
      if(dataArray[0])
        alert(`Annotation ${dataArray[0].annotation.id} found on page with index ${dataArray[0].pageNumber - 1}.`);
      else
        alert('Annotation not found.');
    });


    // find all fields with name field1:
    viewer.findAnnotation(""field1"", {findField: 'fieldName', findAll: true}).then(function(dataArray) {

    });"

    getViewPort Returns PDF page view port information. pageIndex: number Page index (Zero based). number // Get the viewport object for the first page:
    var viewPort = viewer.getViewPort(0);
    goToFirstPage Navigate first page. none void viewer.goToFirstPage();
    goToLastPage Navigate last page. none void viewer.goToLastPage();
    goToNextPage

    Navigate next page.

    none void viewer.goToNextPage();
    goToPageNumber Navigate page with specific page number (numbering starts with 1). 

    pageNumber: number

    void // Go to the second page:
    viewer.goToPageNumber(2);
    goToPrevPage Navigate previous page. none void viewer.goToPrevPage();
    loadAndScrollPageIntoView Method loads a page with the index specified by the pageIndex parameter, and scrolls it to the view. pageIndex: number Required. Destination page index.
    destArray: any[] Optional, The parameter is used for the scrollPageIntoView method after the page is fully loaded.
    Promise // Load and display the first page:
    viewer.loadAndScrollPageIntoView(0);
    loadDocumentList Load an updated document list into document list panel. none void viewer.loadDocumentList();
    newDocument

    Creates and opens a new blank document.

    params: undefined | { confirm?: undefined | false | true; fileName?: undefined | string } Optional, Parameters object: fileName - name of the file for the new document, confirm - show confirmation dialog if document has changes. Promise // Create a new blank document, name the file "test.pdf",
    // display a confirmation dialog if the active document has been modified.
    viewer.newDocument({ fileName: "test.pdf", confirm: true});
    newPage Adds a blank page to the document.

    params: undefined | { height?: undefined | number; pageIndex?: undefined | number; width?: undefined | number } Optional, parameters object: width - page width in points, height - page height in points, pageIndex - page index.

    void // Create a new blank page and insert it in the second position.
    viewer.newPage({pageIndex: 1});
    redoChanges Redo document changes. none void if(viewer.hasRedoChanges) {
      viewer.redoChanges();
    }
    removeAnnotation Remove annotation from document. pageIndex: number
    annotationId: string
    Promise // Remove annotation with id '2R' located on the first page:
    viewer.removeAnnotation(0, '2R');
    repaint Repaint visible pages. none void viewer.repaint();
    saveChanges

    Upload local changes to server.

    none Promise viewer.saveChanges().then(function(result) {
      if(result) {
        alert("The document saved on the server.");
      } else {
        alert("Cannot save the document on the server.");
      }
    });
    scrollAnnotationIntoView Scroll annotation into view.

    pageIndex: number
    annotation: AnnotationBase

    any // Scroll the annotation located on the second page into view.
    viewer.scrollAnnotationIntoView(1, annotation);
    scrollPageIntoView Scroll page into view.
    Usage examples:
    viewer.scrollPageIntoView( { pageNumber: 10 } )
    params: { allowNegativeOffset?: undefined | false | true; destArray?: any[]; pageNumber: number } object. Scroll parameters:
               pageNumber - number. Page number.
               destArray - Array with destination information:
               destArray[0] // not used, can be null, pdf page reference (for internal use only).
               destArray[1] // contains destination view fit type name:
               { name: 'XYZ' }   - Destination specified as top-left corner point and a zoom factor (the lower-left corner of the page is the origin of the coordinate system (0, 0)).
               { name: 'Fit' }   - Fits the page into the window
               { name: 'FitH' }  - Fits the widths of the page into the window
               { name: 'FitV' }  - Fits the height of the page into a window.
               { name: 'FitR' }  - Fits the rectangle specified by its top-left and bottom-right corner points into the window.
               { name: 'FitB' }  - Fits the rectangle containing all visible elements on the page into the window.
               { name: 'FitBH' } - Fits the width of the bounding box into the window.
               { name: 'FitBV' } - Fits the height of the bounding box into the window.
               destArray[2] // x position offset
               destArray[3] // y position offset (note, the lower-left corner of the page is the origin of the coordinate system (0, 0))
               destArray[4] // can be null, contains bounding box width when view name is FitR,
               contains scale when view name is XYZ,
              destArray[5] // can be null, contains bounding box height when view name is FitR
    allowNegativeOffset?: undefined | false | true
    destArray?: any[]
    pageNumber: number
    void

    // Scroll to page 10.
    viewer.scrollPageIntoView( { pageNumber: 10 } )


    // Scroll the annotation bounds rectangle into view:
    var rectangle = annotation.rect;
    var pagePosX = rectangle[0];
    var pagePosY = rectangle[1] + Math.abs(rectangle[3] - rectangle[1]);
    viewer.scrollPageIntoView({ pageNumber: pageIndex + 1, destArray: [null, { name: "XYZ" }, pagePosX, pagePosY, viewer.zoomValue / 100.0] });

    selectAnnotation

    Select annotation for editing.

    pageIndex: number | string Page index (Zero-based) or annotation id.
    annotation: AnnotationBase | string Optional, Annotation id or annotation object itself.
    Promise

    // Select an annotation with id 2R:
    viewer.selectAnnotation("2R");

    // Select an annotation with id 9R located on the last page:
    viewer.selectAnnotation(viewer.pageCount - 1, "9R");

    submitForm Submit form to server.

    submitUrl: string

    void viewer.submitUrl("/CustomFormHandler");
    undoChanges Undo document changes. none void if(viewer.hasUndoChanges) {
      viewer.undoChanges();
    }
    unselectAnnotation

    Reset annotation selection.

    none any viewer.unselectAnnotation();
    updateAnnotation Update annotation.

    pageIndex: number
    annotation: AnnotationBase

    Promise // Update annotation on the first page (page index is 0):
    viewer.updateAnnotation(0, annotation1);
    updateAnnotations Update annotations. pageIndex: number
    annotations: AnnotationBase | AnnotationBase[]
    Promise // Update annotations on the second page (page index is 1):
    var annotationsToUpdate = [annotation1, annotation2];
    viewer.updateAnnotations(1, annotationsToUpdate);
    updateRadioGroupValue

    Update radio buttons group given by parameter fieldName with new field value.

    fieldName: string Grouped radio buttons field name
    newValue: string New fieldValue
    skipPageRefresh: undefined | false | true Optional, boolean. Set to true if you don't need to update page display. Default is false.
    Promise viewer.updateRadioGroupValue("radiogroup1", "3", true);

    Properties

    Property      Description Syntax Return Type Example
    annotations Gets all document annotations. get annotations(): Promise<{ annotations: AnnotationBase[]; pageIndex: number }[]> Promise var viewer = new GcPdfViewer('#root');
    viewer.addDefaultPanels();
    viewer.onAfterOpen.register(function() {
      viewer.annotations.then(function(data) {
        for(var i = 0; i < data.length; i++){
          var pageAnnotationsData = data[i];
          var pageIndex = pageAnnotationsData.pageIndex;
          var annotations = pageAnnotationsData.annotations;
          console.log("Page with index " + pageIndex + " contains " + annotations.length + " annotation(s)");
        }
      });
    });
    viewer.open('Test.pdf');
    beforeUnloadConfirmation Ask the user if he want to leave the page when document is modified.   get beforeUnloadConfirmation(): boolean
    set beforeUnloadConfirmation(enable: boolean)
    boolean var viewer = new GcPdfViewer('#root', { supportApi: 'api/pdf-viewer' } );
     viewer.addDefaultPanels();
     viewer.addAnnotationEditorPanel();
     viewer.addFormEditorPanel();
     viewer.beforeUnloadConfirmation = true;
    canEditDocument Indicates whether opened document can be edited using SupportApi.  get canEditDocument(): boolean boolean if(viewer.canEditDocument) {
      alert("Document editing features enabled.");
    } else {
      alert("Document editing features disabled.");
    }
    currentUserName Gets/sets the current user name. @see userName option. get currentUserName(): string
    set currentUserName(userName: string): void
    string viewer.currentUserName = "John";
    alert("The current user name is " + viewer.currentUserName);
    editMode Gets or sets more precise Edit mode for Annotations or Form editor. get editMode(): EditMode
    set editMode(mode: EditMode): void
    EditMode // Set the layout mode to "Annotation editor"
     viewer.layoutMode = 1;
     // Set the edit mode to "Square".
     viewer.editMode = 4;
    fileData Gets the file data. Available when keepFileData option is set to true. get fileData(): Uint8Array | null   Uint8Array var viewer = new GcPdfViewer('#root', { keepFileData: true });
    viewer.open('Test.pdf');
    viewer.onAfterOpen.register(function() {
      var pdfFileData = viewer.fileData;
    });
    fileName

    Gets the file name that was used to open the document.
     The file name is determined as follows:

    If a local file was opened using the ""Open File"" dialog, returns the local file name;
    else, if a new file was created using the ""newDocument"" method, returns the argument passed to that method;
    else, if options.friendlyFileName is not empty, returns its value;
     else, returns the name generated from the URL passed to the ""open"" method.

    get fileName(): string string var viewer = new GcPdfViewer('#root');
    viewer.onAfterOpen.register(function() {
      alert(""The document is opened, the fileName is "" + viewer.fileName);
    });
    viewer.open('MyDocuments/Test.pdf');
    fileUrl Gets the URL that was used to open the document.
    Returns an empty string when the document was opened from binary data.
    get fileUrl(): string string var viewer = new GcPdfViewer('#root');
    viewer.onAfterOpen.register(function() {
      alert(""The document is opened, the fileUrl is "" + viewer.fileUrl);
    });
    viewer.open('MyDocuments/Test.pdf');
    fingerprint An unique document identifier. get fingerprint(): string string var viewer = new GcPdfViewer('#root');
    viewer.onAfterOpen.register(function() {
      alert(""The document opened, an unique document identifier is ""+ viewer.fingerprint);
    });
    viewer.open('Test.pdf');
    hasChanges Returns true if document has been changed by user. get hasChanges(): boolean boolean if(viewer.hasChanges) {
      alert("The document has been changed.");
    }
    hasCopyData Indicates if buffer contains any data. get hasCopyData(): boolean boolean if(viewer.hasCopyData) {
      viewer.execPasteAction();
    }
    hasDocument  Indicates whether document is loaded into view.   get hasDocument(): boolean boolean if(!viewer.hasDocument) {
      viewer.open("sample.pdf");
    }
    hasRedoChanges Gets a value indicating whether the pdf viewer can redo document changes.  get hasRedoChanges(): boolean boolean if(viewer.hasRedoChanges) {
      viewer.redoChanges();
    }
    hasReplyTool Indicates whether the Reply Tool has been added. get hasReplyTool(): boolean boolean var viewer = new GcPdfViewer('#root');
    if(viewer.hasReplyTool) {
      alert(""The Reply Tool has not been added to the viewer."");
    } else {
      alert(""The Reply Tool has been added to the viewer."");
    }
    viewer.open('Test.pdf');
    hasUndoChanges Gets a value indicating whether the pdf viewer can undo document changes. get hasUndoChanges(): boolean  boolean if(viewer.hasUndoChanges) {
      viewer.undoChanges();
    }
    hideAnnotations Gets if annotations layer is hidden.   get hideAnnotations(): boolean
    set hideAnnotations(hide: boolean): void
    boolean // Hide annotations:
    viewer.hideAnnotations = true;
    layoutMode  Gets or sets the layout mode (Viewer, AnnotationEditor or FormEditor).
    Default layout mode is Viewer.  
    get layoutMode(): LayoutMode
    set layoutMode(mode: LayoutMode): void
    LayoutMode // Set the layout mode to "Form editor"
     viewer.layoutMode = 2;
    onAfterOpen Occurs when a document is opened. get onAfterOpen(): EventFan<AfterOpenEventArgs> EventFan var viewer = new GcPdfViewer('#root');
    viewer.onAfterOpen.register(function() {
      alert("The document opened.");
    });
    viewer.open('Test.pdf');
    onBeforeOpen Occurs immediately before the document opens. get onBeforeOpen(): EventFan<BeforeOpenEventArgs>  EventFan var viewer = new GcPdfViewer('#root');
    viewer.onBeforeOpen.register(function(args) {
      alert("A new document will be opened,\n payload type(binary or URL): " + args.type +",\n payload(bytes or string): " + args.payload);
    });
    viewer.open('Test.pdf');
    onError The event indicating error. get onError(): EventFan<ErrorEventArgs> EventFan

    var viewer = new GcPdfViewer('#root');
    viewer.addDefaultPanels();
    viewer.onError.register(handleError);
    viewer.open('Test.pdf');

    function handleError(eventArgs) {
        var message = eventArgs.message;
        if (message.indexOf("Invalid PDF structure") !== -1) {
            alert('Unable to load pdf document, pdf document is broken.');
        } else {
            alert('Unexpected error: ' + message);
        }
    }

    options The viewer options.  get options(): Partial<ViewerOptions>
    set options(options: Partial<ViewerOptions>): void
    Partial viewer.options.zoomByMouseWheel = { always: true };
    viewer.applyOptions();
    pageCount Gets pages count. get pageCount(): number number var viewer = new GcPdfViewer('#root');
    viewer.onAfterOpen.register(function() {
      alert("The document opened. Total number of pages: " + viewer.pageCount);
    });
    viewer.open('Test.pdf');
    pageIndex Gets/sets the active page index. get pageIndex(): number
    set pageIndex(val: number): void
    number var viewer = new GcPdfViewer('#root');
    viewer.onAfterOpen.register(function() {
      // Navigate page with index 9:
      viewer.pageIndex = 9;
    });
    viewer.open('Test.pdf');
    rightSidebar Gets right sidebar object.
    Use this object if you want to manipulate the right sidebar.
    get rightSidebar(): GcRightSidebar  GcRightSidebar viewer.rightSidebar.show('expanded', 'reply-tool');
    viewer.rightSidebar.toggle();
    viewer.rightSidebar.hide();
    viewer.rightSidebar.expand();
    viewer.rightSidebar.collapse();
    rotation Gets rotation in degrees.  get rotation(): number
    set rotation(degrees: number): void
    number var viewer = new GcPdfViewer('#root');
    // Register an onAfterOpen event handler:
    viewer.onAfterOpen.register(function() {
      // Apply 90 degree clockwise rotation:
      viewer.rotation = 90;
    });
    // Open document:
    viewer.open('Test.pdf');
    supportApi Gets the SupportApi client. get supportApi(): ISupportApi | null ISupportApi var viewer = new GcPdfViewer('#root', { supportApi: 'api/pdf-viewer' } );
     // Contact server and get Support API version.
     viewer.serverVersion.then(function(ver) {
         alert("The SupportApi version is " + ver);
     });
    toolbarLayout Defines toolbar layout for different viewer modes: viewer, annotationEditor, formEditor. get toolbarLayout(): GcPdfViewerToolbarLayout
    set toolbarLayout(toolbarLayout: GcPdfViewerToolbarLayout): void
    GcPdfViewerToolbarLayout viewer.toolbarLayout.viewer.default = ["open", "save"];
    viewer.toolbarLayout.annotationEditor.default = ["open", "save", "$split", "new-document", "edit-ink", "edit-text"];
    viewer.toolbarLayout.formEditor.default = ["open", "save", "$split", "edit-widget-tx-field", "edit-widget-tx-password"];
    viewer.applyToolbarLayout();
    undoCount Gets total undo changes count. get undoCount(): number  number  alert("Undo levels count is " + viewer.undoCount);
    undoIndex Gets current undo changes index. get undoIndex(): number  number  alert("The current Undo level index is " + viewer.undoIndex);
    zoomMode Gets/sets the current zoom node.
    Accepted values are: 0 - Value, 1 - PageWidth, 2 - WholePage.
             
    // Set zoom mode to 'WholePage'
    viewer.zoomMode = 2;
    get zoomMode(): ZoomMode
    set zoomMode(val: ZoomMode): void
    ZoomMode // Set zoom mode to 'WholePage'
    viewer.zoomMode = 2;
    version Returns current PDF viewer version. get version(): string string alert("The GcPdfViewer version is " + viewer.version);
    zoomValue Gets/sets the current zoom percentage level. get zoomValue(): number
    set zoomValue(val: number): void
    number // Set zoom value to 150%
    viewer.zoomValue = 150;
    i18n Gets i18next instance which can be used to add viewer translations.
             See https://www.i18next.com for details about i18next framework.
    static get i18n(): i18n i18n function loadPdfViewer(selector) {
      // You can load translations from any source (see en-pdf-viewer.json for an example):
      var myTranslations = {
            "toolbar": {
                "open-document": "Open MY document",
                "pan": "My Pan tool",
            }
       };
       // Initialize translations:
       GcPdfViewer.i18n.init({
         resources: { myLang: { translation: myTranslations } }
       }).then(function(t) {
         // New translations initialized and ready to go!
         // Now create PDF viewer:
         var viewer = new GcPdfViewer(selector, { language: 'myLang' });
         viewer.addDefaultPanels();
         //viewer.open("sample.pdf");
       });
    }
    loadPdfViewer('#root');
    isUpdating Returns true if notifications suspended by calls to @see:beginUpdate. get isUpdating(): boolean boolean var isUpdatingFlag = viewer.isUpdating;

    Events

    Event Description Example
    get onError(): EventFan<ErrorEventArgs> Indicates errors while loading PDF documents.

    function loadPdfViewer()
    {
    var viewer = new GcPdfViewer('#root');
    viewer.addDefaultPanels();
    viewer.onError.register(handleError);
    viewer.open('Test.pdf');
    function handleError(eventArgs)
    {
    var message = eventArgs.message;
    if (message.indexOf("Invalid PDF structure") !== -1)

    alert('Unable to load pdf document, pdf document is broken.');
    }
    else {
    alert('Unexpected error: ' + message);
    }
    }