Document Viewer for Developers

From Sense/Net Wiki
Jump to: navigation, search
  •  
  •  
  •  
  •  
  • 100%
  • 6.3
  • Enterprise
  • Community
  • Planned

Overview

Document Viewer
Managing Office documents is a popular feature in every ECM system. Sense/Net ECM also comes with built-in Sense/Net Document Viewer helps users to read your documents in the browser, and complete them with highlights, redactions and annotations to facilitate collaboration.

Document Viewer helps users to read documents in the browser without needing another document viewer plugin or software. The Document Viewer shows the preview images of the document there are generated by upload (when you upload a file – e.g. a Word document – images are saved from the documents pages). You can learn more about preview generation here.

Document Viewer

Document viewer’s basic functionality is to read a document in the browser. Actually it is not the document that you can read in the viewer only its pre-generated preview images. So users without the right permissions can’t reach the original document, they can only see the preview images. There are some special permissions from version 6.3 which are related to the document viewer.

Restricted preview

All fields of the document can be accessed except the documents binary, so the users who have only this permission can’t download the original document and can’t see the text under redacted parts of the document even when they browse the preview images outside the Document Viewer.

Preview without watermark

Users who have this permission can see the watermarked document without watermark. For these users a button is shown in the toolbar to hide and show watermark. For users without this permission this button is hidden.

Preview without redaction

Users who have this permission can see the redacted document without redactions and can edit the available redactions and add new redactions. For users without these permission redactions can’t be hidden they are generated on the preview image.

Add/edit annotations, highlights and redactions

Adding annotations highlights and redactions are going the same way. There’re three canvases for the three functions over the pages of the document and there’s a fourth technical canvas to help the drawing, resizing and positioning issues. When you select a button the related canvas will be positioned over the others and you can draw – add and edit shapes - on it. You can add a shape by double clicking on the selected canvas or select a rectangular area by drawing. If you add the shape by double clicking, the shape will have a default size but if you’ve add it with drawing a rectangle, the shape will have the same size that the drawn area.

An available shape can be resized and repositioned by the user with the right permission. If the chosen button is selected and the related canvas is selected also, you can select shapes on the chosen canvas by clicking on it and after that it can be moved with drag and drop or resized with the marked points around the shape. Move and resize are processing on the technical canvas and after the end of the activity they will be moved on the chosen canvas and removed from the technical canvas.

Save annotations, highlights and redactions

If a user has ‘Save’ permission he can save the added/edited shapes to the document. These shapes aren’t saved in the documents binary but the document content type has a longtext field to store shape information in JSON format. The document viewer uses this field’s content to redraw saved shapes after reload the document previews in the Document Viewer.

[{
"redactions":[{"x":85.68852240366039,"y":91.66401273885349,"w":568.9490445859872,"h":29.50106157112525,"imageIndex":1,"index":0}]
},{
"highlights":[{"x":92.01017845461574,"y":339.2622080679405,"w":613.200636942675,"h":91.66401273885344,"imageIndex":1,"index":0}]
},{
"annotations":[]
}]

While the user edit/add annotations, highlights or redactions to the previews the Document Viewer stores the shape information in the background. This stored information can be given to a save/burn functionality.

Save page orientations

If a user has ‘Save’ permission he can save the rotation data of the document's pages. Page orientation aren’t saved in the documents binary but the document content type has a longtext field to store rotation data in JSON format. The document viewer uses this field’s content to reload pages with the saved orientation.

[{
    "pageNum":"1",
    "options":{"degree":90}
 },
 {
    "pageNum":"2",
    "options":{"degree":-90}
}]

When the user rotates a page in the Document Viewer, it stores the rotation data in the background. This stored information can be given to a save/burn functionality.

Please note that edit/add annotation, redaction or highlight functionality is disabled on rotated pages.

Only the original preview images are stored, with the original orientation (which may be landscape actually, if a page was rotated originally in Word for example). When you rotate images in the viewer and save these modifications, it is the viewer's responsibility to get the images with the appropriate orientation. There is a simple URL parameter for this (called rotation) that you can use when requesting individual preview images:

  • .../Previews/v2.0A/preview1.png?rotation=90

The rotated images will also appear correctly when we generate a PDF document from these preview images on the server.

Watermark

Watermark can be set on every document or globally (on a folder, a workspace or sitewide). You can set the watermark text in the watermark field of a document or in the DocumentPreview.setting file. In the DocumentPreview.setting file you can enable the watermark functionality and set the watermark text or customize watermark texts font type, wegight, style, color, opacity or position.

You can learn more about Settings here.

Getting started

You can bind the Document Viewer to a common html container element just like other jQuery plugins.

First create a container element:

<div id=”documentViewer”></div>

Initialize the Query builder via a jQuery selector:

     $dv.documentViewer({
	getImage: functionName,
	getThumbnail: functionName,
	showthumbnails: true,
	metadata: true,
        showtoolbar: true,   
        edittoolbar: true,                              
        title: 'My document', 
	containerWidth:1024,
	containerHeight:500,
        reactToResize: true, 
	metadataHtml: ’’,
        isAdmin: isAdmin, 
        showShapes: true,
        shapes: '<%=GetValue("Shapes") %>',
        SR: resourceArray,
        functions: {
	    print: {
		action: yourPrintFunctionName,
		title: „Print”,
		icon: html
		type: ’dataRelated’,
		touch: false
            }
        }
        previewCount : '<%= previewCount %>',
        filePath : filePath,
        fitContainer : true
     });

Configuring the Document Viewer jQuery plugin

getImage function (default: null)

The function that gives the path of a previewimage for pagenumber. (this function will be called, when the docviewer want to display a page)

getExistingPreviewImages function (default: null)

The function that gives an array with the paths, index, width and height of all the previewimages that are already generated. (this function will be called, when the docviewer initializing)

getThumbnail function (default: null)

The function that gives the path of a thumbnailimage for a pagenumber. (this function will be called when the docviewer want to display a thumbnail)

showthumbnails Boolean (default: true)

You can set visibility of thumbnail images.

metadata Boolean (default: false)

You can set visibility of metadata but it isn’t visible if the ‘metadataHtml’ is empty.

showtoolbar Boolean (default: false)

You can set visibility of the toolbar.

edittoolbar Boolean (default: false)

You can set visibility of the editor toolbar width annotation, highlight and redaction buttons.

title String (default: null)

You can set the title of the document. It will be shown in the toolbar.

containerWidth Number (default: $container.width())

You can set a special width to size the Document viewer. If you leave this property empty, the plugin will calculate viewer’s width from elements width. This property is useful if you want to use different widths on different devices e.g. tablets, mobile phones.

containerHeight Number (default: $container.height())

You can set a special height to size the Document viewer. If you leave this property empty, the plugin will calculate viewer’s height from elements height. This property is useful if you want to use different heighta on different devices e.g. tablets, mobile phones.

reactToResize Boolean (default: false)

Set it to true if you want to resize document viewer dynamically when the browser window is resized.

metadataHtml String (default: null)

You can set here what Document Viewer show in the metadata section. It can be html or simple text.

isAdmin Boolean (default: false)

You can give to the viewer if the current user has the Save permission. It can work dynamically if you get the permissions of the current user for example trough OData and give it to the Document Viewer plugin.

If this property is true all the buttons will be shown in the toolbar, and the user can edit/hide redactions and watermark. So it’s recommended to test current users ‘Save permission’ outside the plugin and give its result to the Document Viewer.

You can learn more about GetPermission OData action in Built-in OData actions.

showShapes Boolean (default: true)

You can set the visibility of shapes over the previews. If it’s set to true, the shapes will be displayed when the document is loaded. If it’s set to false the shapes will not appear but you can display them by clicking on the ‘Show shapes’ button.

shapes Object (default: null)

You must set the shapes of the document. The shapes are stored in one of the documents field in JSON format. You can get the value of this field the way that you preferred.

pageAttributes Object (default: null)

You must set where the document's page orientation data is stored. This data is stored in one of the documents field in JSON format. You can get the value of this field the way that you preferred.

SR Object (default: null)

You can set custom string resources to the Document Viewer but we recommend to change them in the /Root/Localization/SN_DocViewer.xml string resource file.

functions

Additional functions can be added here in json format. DocViewer will iterate over these functions and add them to the toolbar. Functions can be customize with the following options (e.g. Print functionality)

     functions: {
         print: {
            action: printDocument,
            title: SN.Resources.DocViewer["DocViewer-toolbarPrint"],
            icon: '<span class="sn-icon sn-icon-print"></span>',
            type: 'dataRelated',
            touch: false,
	    permission: Save
         }
     }
action function (default: null)

This function will be called when the user click on the toolbar button of the function.

title String (default: empty string)

This will be the title of the toolbar button.

type 'dataRelated' or 'drawingRelated' (default: 'dataRelated')

If you set type to ‘drawingRelated’ your custom functions button will be displayed next to the redaction button. If you choose dataRelated, the button will be displayed at the end of the toolbar.

icon String (default: empty string)

You can add html to display as button/link in the toolbar.

touch Boolean (default: false)

You can choose whether your function will be displayed on touch devices or not.

permission Boolean (default: false)

You can add a function that you can return whether the current user can see the functions button in the toolbar or not. For example Save function is only enabled for a user who has a Save permission, so you create a function that return true only when the current user has Save permission for the current content and you call this function in this permission option. The option expects only true or false as a value.

getPC function (default: null)

The function that gives the actual pagecount and can be called from the plugin. (this function will be called, when the docviewer is refreshed)

getShapes function (default: null)

The function that gives the actual document's shapes and can be called from the plugin. (this function will be called, when the docviewer is refreshed)

Methods

setZoomLevel

Sets the current zoom level of the viewer.

Parameters:
newLevel required | integer | (default: 1)
The chosen zoom rate.
x0 optional | integer | (default: null)
The chosen x coordinate.
y0 optional | integer | (default: null)
The chosen y coordinate.
$rel optional | object | (default: technicalCanvas)
This will be the selected top canvas after zooming.
rb optional | boolean | (default: false)
Set it to true if you use the rubberband zoom.
viewer = $dv.data('snDocViewer');
viewer.setZoomLevel(2);


enterFullscreenMode

Enters fullscreen mode.

viewer = $dv.data('snDocViewer');
viewer.enterFullscreenMode();


exitFullscreenMode

Exits fullscreen mode.

viewer = $dv.data('snDocViewer');
viewer.exitFullscreenMode();


destroy

Destroys the current plugin instance and closes the document.

viewer = $dv.data('snDocViewer');
viewer.destroy;


getAllShapes

Returns the array which contains all shapes of the current document.

viewer = $dv.data('snDocViewer');
var shapes = viewer.getAllShapes();


isUnsaved

Returns true if the document has unsaved changes. There's a boolean property in the background ('unsaved') which is set to true, if a user modified something related to the document (redaction, highlight, etc.)

viewer = $dv.data('snDocViewer');
if(viewer.isUnsaved){
  //do something
}


setUnsaved

Sets unsaved property. You can set it to false in your custom save method, when the latest modifications are saved.

Parameters:
isUnsaved required | boolean | (default: false)
viewer = $dv.data('snDocViewer');
viewer.setUnsaved(false);


isFullscreen

Tells if the viewer is in fullscreen mode.

viewer = $dv.data('snDocViewer');
if(viewer.isFullscreen()){
  //do something
}


zoomLevel

Gets the current zoom level of the viewer.

viewer = $dv.data('snDocViewer');
var zoomLevel = viewer.zoomLevel();


getContainer

Gets the container DOM element of the viewer.

viewer = $dv.data('snDocViewer');
var $container = viewer.getContainer();


getViewport

Gets the viewport element of the viewer.

viewer = $dv.data('snDocViewer');
var $docpreview = viewer.getViewport();


getViewerId

Gets the identifier of this viewer.

viewer = $dv.data('snDocViewer');
var viewerID = viewer.getViewerId();


scheduleRedraw

Schedules a redraw for the viewer.

viewer = $dv.data('snDocViewer');
viewer.scheduleRedraw();


changePage

Changes the currently displayed page in the viewer.

Parameters:
page required | integer | (default: 1)
The number of the page which you want to display.
viewer = $dv.data('snDocViewer');
viewer.changePage(5);


currentPage

Gets the current page the viewer is on.

viewer = $dv.data('snDocViewer');
var currentPageNumber = viewer.currentPage();


calledPage

Gets number of the called page.

viewer = $dv.data('snDocViewer');
var calledPageNumber = viewer.calledPage();


pageCount

Gets the number of pages the current document has.

viewer = $dv.data('snDocViewer');
var pageCount = viewer.pageCount();


loadedImages

Gets the number of the loaded preview pages (array).

viewer = $dv.data('snDocViewer');
var loadedImages = viewer.loadedImages();


pageIsLoaded

Tells when a preview page image is loaded.

Parameters:
page required | integer | (default: 1)
The number of the page.
viewer = $dv.data('snDocViewer');
if(viewer.pageIsLoaded(3)){
  //do something
}


canvasesAreLoaded

Tells when all canvases of a preview page are loaded.

Parameters:
page required | integer | (default: 1)
The number of the page.
viewer = $dv.data('snDocViewer');
if(viewer.canvasesAreLoaded(3)){
  //do something
}


saveShapes

Returns the shapes and the page rotation data of the current document in an array.

viewer = $dv.data('snDocViewer');
var savable = viewer.saveShapes();
savable.Path = filePath;
   var p = odata.saveContent({
       contentItem: savable
   }).done(function () {
       overlayManager.showMessage({
           type: "success",
           title: SN.Resources.DocViewer["MessageBox-Success"],
           text: SN.Resources.DocViewer["DocViewer-burnSuccessful"]
   });
});


setPageAccordingToScroll

Sets the viewers current page related properties according to scroll.

viewer = $dv.data('snDocViewer');
viewer.setPageAccordingToScroll();


appendPreviewPostfix

Set url postfixes (e.g. '&watermark=true').

Parameters:
url required | string | (default: null)
Path of the preview or thumbnail image.
addWatermark optional | boolean | (default: false)
Adds the watermark prefix to the image url (&watermark=true).
addNoCache optional | boolean | (default: false)
Adds the nocache prefix to the image url (&nocache=date).
viewer = $dv.data('snDocViewer');
appendPreviewPostfix = viewer.appendPreviewPostfix;
if (viewer.appendPreviewPostfix && typeof appendPreviewPostfix == "function") {
    var wmParam = '&watermark=true';
    $images.each(function (i) {
        var $img = $($images[i]);
        var oldsrc = $img.attr('src');
        var hadNoCache = oldsrc.indexOf('&nocache=') > 0;
        var newsrc = null;
        // Set the src parameter according to the watermark URL parameter
        var questionMarkPos = oldsrc.indexOf('?');
        var newsrc = (questionMarkPos > 0) ? oldsrc.substring(0, questionMarkPos) : oldsrc;
        newsrc = appendPreviewPostfix(newsrc, enabled, hadNoCache);
        $img.attr('src', newsrc);
    });
}


refreshViewer

Refreshes the viewer according to the document changes.

Parameters:
refreshPager optional | boolean | (default: false)
If it's set to true, the pager of the viewer will be refreshed.
refreshPreviews optional | boolean | (default: false)
If it's set to true, the preview images will be refreshed.
refreshThumbnails optional | boolean | (default: false)
If it's set to true, the thumbnail images will be refreshed.
viewer = $dv.data('snDocViewer');
$('#refreshButton').on('click', function(){
  viewer.refreshViewer(true, true, true)
});


refreshEditorButtons

It allows you to add and set additional properties on the editor buttons (annotation, highlight, redaction).

Parameters:
buttonArray required | Array | (default: null)
An array of name and value pairs that you want to add as properties to the buttons (e.g. disabled)
viewer = $dv.data('snDocViewer');
 
function adminbutton(name, buttonAdditonalProperties) {
   this.name = name;
   this.additionalProps = buttonAdditonalProperties;
}
 
$('#disable').on('click', function(){
     buttonArray = [];
     buttonArray[0] = new adminbutton('annotation',{disabled: true});
     buttonArray[1] = new adminbutton('highlight',{disabled: false});
     buttonArray[2] = new adminbutton('redaction',{disabled: false});
     viewer.refreshEditorButtons(buttonArray);
}

Callbacks

documentOpened

Called when the document was opened, ie. when this plugin was initialized

   $dv.documentViewer({
         ...
         callbacks: {
            documentOpened: function(){
                // Get time
                var now = moment();
                lastPageChangeTime = now;
                ...
            }
         }
     });


documentClosed

Called when the document is closed, ie. when either the plugin is destroyed or the window is unloaded

   $dv.documentViewer({
         ...
         callbacks: {
            documentClosed: function(){
                // Calculate time spent
                var now = moment();
                var timeSpentOnDocument = 0;
                var timeSpentOnPage = now.diff(lastPageChangeTime, 'seconds');
                ...
            }
         }
     });


pageChanged

Called after going to a different page of the document (parameter: page number) NOTE: this is called when the user scrolls to a different page, or clicks a thumbnail, or when the viewer otherwise goes to a different page

   $dv.documentViewer({
         ...
         callbacks: {
            pageChanged: function(page){
                // Calculate time spent
                var now = moment();
                var timeSpentOnPage = now.diff(lastPageChangeTime, 'seconds');
                timeSpentOnEachPage[lastPage] = (timeSpentOnEachPage[lastPage] || 0) + timeSpentOnPage;
                // Reset time
                lastPageChangeTime = now;
                lastPage = page;
            }
         }
     });


contextMenuShown

Called after a context menu is shown (parameter: context menu object)

   $dv.documentViewer({
         ...
         callbacks: {
            contextMenuShown: function($cm) {
               // do something
            }
         }
     });


zoomLevelChanged

Called when the zoom level is changed

   $dv.documentViewer({
         ...
         callbacks: {
            zoomLevelChanged: function() {
               // do something
            }
         }
     });


viewerError

Called when an error happened in the viewer

   $dv.documentViewer({
         ...
         callbacks: {
            viewerError: function(errorMessage) {
                overlayManager.showMessage({
                    type: "error",
                    title: errorMessage,
                    text: errorMessage
                });
            }
         }
     });


documentChanged

Called when the document was changed, ie. when a shape is added

   $dv.documentViewer({
         ...
         callbacks: {
            documentChanged: function() {
                //do something
            }
         }
     });


rotationStarted

Called when the rotation is started.

   $dv.documentViewer({
         ...
         callbacks: {
            rotationStarted: function() {
                //do something
            }
         }
     });


rotationEnded

Called when the rotation is ended.

   $dv.documentViewer({
         ...
         callbacks: {
            rotationEnded: function() {
                //do something
            }
         }
     });


loadingStarted

Called when the preview loading is started.

   $dv.documentViewer({
         ...
         callbacks: {
            loadingStarted: function() {
                //do something
            }
         }
     });


loadingEnded

Called when the preview loading is ended.

   $dv.documentViewer({
         ...
         callbacks: {
            loadingEnded: function() {
                //do something
            }
         }
     });

OData actions and functions for Preview

There are a couple of built-in OData methods for customizing the preview plugin:

Document Viewer on tablet

Document viewer can be used on tablets but with reduced functionality. On these devices we integrated a jQuery plugin named [iScroll] to the Document Viewer to get pinch zooming, double tap zooming, fancy scrolling and many more.