Some test text!

Realtime collaboration

In this document
chevron_rightSetting up realtime collaboration with WebViewer and Firebase
chevron_rightInitial setup - HTML
chevron_rightServer - JavaScript
chevron_rightClient - JavaScript

linkSetting up realtime collaboration with WebViewer and Firebase

WebViewer contains APIs that allow you to export/import annotations from/to a document. Using those APIs and a server, you can set up realtime collaboration easily. This guide provides a simple example that covers:

  • Authenticating users
  • Exporting/Importing annotation data to/from server
  • Setting the user permissions of each annotation on both server and client side

You can find the full version of the sample in your download package, WebViewer/samples/annotation/realtime-collaboraiton/.

linkInitial setup - HTML

  1. Download the WebViewer SDK and unzip the package.

  2. Copy lib/ folder to a location on your web server.

  3. Create an HTML page.

  4. Add the WebViewer script to the <head> of the HTML page.

    <script src="lib/webviewer.min.js"></script>
  5. Add necessary scripts server methods. In this guide, we are going to include Firebase library and a separate file named server.js

    <script src=""></script>
    <script src="server.js"></script>
  6. Add a script to initiate and use WebViewer.

    <script src="main.js"></script>
  7. Create a <div> tag in the HTML <body> and give it an id. This will be the container for the WebViewer

    <div id="viewer"></div>

linkServer - JavaScript

In realtime collaboration, a server will merely act as an online database that triggers events upon data creation/modification/deletion. As long as the above requirement is met, your server can be built in any language and stack of your choice. For the simplicity of this guide, we will be using Firebase.

  1. Go to the Firebase Console, login and create a project.
  2. Click "Add Firebase to your Web App" and copy the whole code for "Initializing Firebase". If storageBucket is empty, close the popup and try again (that's a known bug from Firebase).
  3. Create a JavaScript file and name it server.js.
  4. Paste the code that you have copied from Firebase. (Note that you should remove the script tags)
  5. Store the firebase.database.References for annotations and users. We will use these to create/update/delete data, and listen to data change events as well.
window.Server = function() {
  var config = {
    apiKey: "YOUR_API_KEY",
    authDomain: "",
    databaseURL: "",
    storageBucket: "",
    messagingSenderId: "YOUR_SENDER_ID"

  this.annotationsRef = firebase.database().ref().child('annotations');
  this.authorsRef = firebase.database().ref().child('authors');
  1. Create a custom bind function for authorization and data using firebase.auth.Auth#onAuthStateChanged and firebase.database.Reference#on.
Server.prototype.bind = function(action, callbackFunction) {
  switch(action) {
    case 'onAuthStateChanged':
    case 'onAnnotationCreated':
      this.annotationsRef.on('child_added', callbackFunction);
    case 'onAnnotationUpdated':
      this.annotationsRef.on('child_changed', callbackFunction);
    case 'onAnnotationDeleted':
      this.annotationsRef.on('child_removed', callbackFunction);
      console.error('The action is not defined.');
  1. Define a method to check if author exists in the database. We will use firebase.database.Reference#once and firebase.database.DataSnapshot#hasChild to do so.
Server.prototype.checkAuthor = function(authorId, openReturningAuthorPopup, openNewAuthorPopup) {
  this.authorsRef.once('value', function(authors) {
    if (authors.hasChild(authorId)) {
      this.authorsRef.child(authorId).once('value', function(author) {
    } else {
  1. Define a sign-in method. In this guide, we will use firebase.auth.Auth#signInAnonymously.
Server.prototype.signInAnonymously = function() {
  firebase.auth().signInAnonymously().catch(function(error) {
    if (error.code === 'auth/operation-not-allowed') {
      alert('You must enable Anonymous auth in the Firebase Console.');
    } else {
  1. From the Firebase console click the "Authentication" button on the left panel and then click the "Sign-in Method" tab, just to the right of "Users". From this page click the "Anonymous" button and choose to enable Anonymous login.

  2. Define data-write methods using firebase.database.Reference#set and firebase.database.Reference#remove.

Server.prototype.createAnnotation = function(annotationId, annotationData) {

Server.prototype.updateAnnotation = function(annotationId, annotationData) {

Server.prototype.deleteAnnotation = function(annotationId) {

Server.prototype.updateAuthor = function(authorId, authorData) {

Last but not least, you should add server-side permission rules for writing data. Although client-side permission checking is supported in WebViewer, every user does have access to each annotation's information (including authorId and authorName). Thus, data-write permission should be regulated in the server as well. In this guide, we have used Firebase's Database Rules.

  1. Copy the JSON below and paste it in your Firebase Console's Database Rules. From the console click the "Database" button on the left panel and then click the "Rules" tab, just to the right of "Data". This will make sure that trying to modify someone else's annotation isn't allowed.
  "rules": {
    ".read": "auth != null",

    "annotations": {
      "$annotationId": {
        ".write": "auth.uid === newData.child('authorId').val() || auth.uid === data.child('authorId').val() || auth.uid === newData.child('parentAuthorId').val() || auth.uid === data.child('parentAuthorId').val()"

    "authors": {
      "$authorId": {
        ".write": "auth.uid === $authorId"

linkClient - JavaScript

  1. Create a JavaScript file and name it main.js.
  2. Instantiate WebViewer on a DOM element, making sure to wrap this code and any further code inside $(document).ready(). Initial document can be any PDF or XOD file.
$(document).ready(function() {
  var viewerElement = document.getElementById('viewer');
  var myWebViewer = new PDFTron.WebViewer({
    path: "lib",
    initialDoc: "MY_INITIAL_DOC.pdf",
    documentId: "unique-id-for-this-document"
  }, viewerElement);

  1. Create the server.

    var server = new Server();
  2. Bind a callback function to DocumentViewer.documentLoaded event. You will then be able to get annotationManager and access its methods.

viewerElement.addEventListener('documentLoaded', () => {
  var annotationManager = myWebViewer.getInstance().docViewer.getAnnotationManager();
  // Code in later steps will come here...
  1. Inside the documentLoaded callback, bind another callback function to server's onAuthStateChanged event that is defined in server.js. A firebase.User object will be passed as a parameter.

    1. If the user is not logged in we'll call the sign-in method that we defined in server.js.
    2. If the user is logged in, we'll store their uid in the authorId variable, which will be used for client-side annotation permission checks.
    3. We call server.checkAuthor with parameters authorId, openReturningUserPopup function and openNewUserPopup function. These functions will be discussed in next steps.
    4. Then, we will send author information to the server and bind callback functions to annotation events. Details of the callback functions will be discussed in next steps.
var authorId = null;

server.bind('onAuthStateChanged', function(user) {
  // User is logged in
  if (user) {
    // Using uid property from Firebase Database as an author id
    // It is also used as a reference for server-side permission
    authorId = user.uid;
    // Check if user exists, and call appropriate callback functions
    server.checkAuthor(authorId, openReturningAuthorPopup, openNewAuthorPopup);
    // Bind server-side data events to callback functions
    // When loaded for the first time, onAnnotationCreated event will be triggered for all database entries
    server.bind('onAnnotationCreated', onAnnotationCreated);
    server.bind('onAnnotationUpdated', onAnnotationUpdated);
    server.bind('onAnnotationDeleted', onAnnotationDeleted);
  // User is not logged in
  else {
    // Login
  1. Define callback functions for annotationCreated, annotationUpdated and server.annotationDeleted events. A data object will be passed as a parameter. For more information, refer to firebase.database.DataSnapshot.

    1. openReturningAuthorPopup is a callback function triggered when author data is found in the database. It will receive authorName as a parameter, and open a popup with the authorName as a visual feedback.
    2. openNewAuthorPopup is a callback function triggered when author data is not found. Then we will open a popup for a new author to setup an author name.
    3. updateAuthor is a function which will set author name in both client and server using annotationManager.setCurrentUser and server.updateAuthor, respectively.
function openReturningAuthorPopup(authorName) {
  // The author name will be used for both WebViewer and annotations in PDF
  // Open popup for the returning author
  window.alert(`Welcome back ${authorName}`);

function openNewAuthorPopup() {
  // Open prompt for a new author
  var name = window.prompt('Welcome! Tell us your name :)');
  if (name) {

function updateAuthor(authorName) {
  // The author name will be used for both WebViewer and annotations in PDF
  // Create/update author information in the server
  server.updateAuthor(authorId, { authorName });
  1. Define callback functions for annotationCreated, annotationUpdated and server.annotationDeleted events. A data object will be passed as a parameter. For more information, refer to firebase.database.DataSnapshot.

    1. onAnnotationCreated and onAnnotationUpdated have the exact same behavior in this guide. They will use annotationManager.importAnnotCommand to update the viewer with the xfdf change.
    2. We also set a custom field authorId for the updated annotation to control client-side permission of the created/updated annotation.
    3. onAnnotationDelete creates a delete command string from the annotation's id and is simply able to call importAnnotCommand on it.
function onAnnotationCreated(data) {
  // data.val() returns the value of server data in any type. In this case, it
  // would be an object with properties authorId and xfdf.
  var annotation = annotationManager.importAnnotCommand(data.val().xfdf)[0];
  annotation.authorId = data.val().authorId;
  myWebViewer.getInstance().fireEvent('updateAnnotationPermission', [annotation]);

function onAnnotationUpdated(data) {
  // Import the annotation based on xfdf command
  var annotation = annotationManager.importAnnotCommand(data.val().xfdf)[0];
  // Set a custom field authorId to be used in client-side permission check
  annotation.authorId = data.val().authorId;

function onAnnotationDeleted(data) {
  // data.key would return annotationId since our server method is designed as
  // annotationsRef.child(annotationId).set(annotationData)
  var command = '<delete><id>' + data.key + '</id></delete>';
  1. After server callback functions are bound, we'll also bind a function to annotationManager.annotationChanged event.

    1. First parameter, e, has a property imported that is set to true by default for annotations internal to the document and annotations added by importAnnotCommand or importAnnotations.

      This is key since we know that any annotationChanged event that wasn't imported was triggered on the client. So the annotations were added/modified/deleted by the current user.
    2. Then we iterate through the annotations that are changed, which is passed as the second parameter.
    3. Third parameter, type, defines which action it was. In this guide, we'll have the same behavior for both add and modify action types.
    4. When annotations are added and modified, we will call server.createAnnotation or server.updateAnnotation which needs four variables: annotationId, authorId, parentAuthorId and xfdf.
    5. annotationId can be retrieved from annotation.Id.
    6. authorId was saved as a reference when user logged in.
    7. parentAuthorId refers to the parent annotation's author id, if any. This will be used to distinguish replies, and will be referenced in server-side permission. Thus, we retrieve authorId of the parent annotation by using annotation.InReplyTo, which returns the annotation id of the parent annotation.
    8. xfdf can be retrieved using annotationManager.getAnnotCommand. It will get an XML string specifying the added, modified and deleted annotations, which can be used to import the annotation using (annotationManager.importAnnotCommand)[/api/web/CoreControls.AnnotationManager.html#importAnnotCommand] in server data callback functions.
annotationManager.on('annotationChanged', function(e, annotations, type) {
  if (e.imported) {
  annotations.forEach(function(annotation) {
    if (type === 'add') {
      var xfdf = annotationManager.getAnnotCommand();
      var parentAuthorId = null;
      if (annotation.InReplyTo) {
        var parentAuthorId = annotationManager.getAnnotationById(annotation.InReplyTo).authorId || 'default';
      server.createAnnotation(annotation.Id, {
        authorId: authorId,
        parentAuthorId: parentAuthorId,
        xfdf: xfdf
    } else if (type === 'modify'){
      var xfdf = annotationManager.getAnnotCommand();
      var parentAuthorId = null;
      if (annotation.InReplyTo) {
        var parentAuthorId = annotationManager.getAnnotationById(annotation.InReplyTo).authorId || 'default';
      server.updateAnnotation(annotation.Id, {
        authorId: authorId,
        parentAuthorId: parentAuthorId,
        xfdf: xfdf
    } else if (type === 'delete') {
  1. Lastly, we will overwrite the client-side permission checking function using annotationManager.setPermissionCheckCallback. The default is set to compare the authorName. Instead, we will compare authorId created from the server.
annotationManager.setPermissionCheckCallback(function(author, annotation) {
  return annotation.authorId === authorId;


At this point you should be able to have multiple people access the HTML page from your server and add/modify/delete annotations in real time. To test it out yourself you could try opening it in multiple browsers or in an incognito window to simulate multiple users.