PDF.js Express Plusplay_arrow

Professional PDF.js Viewing & Annotations - Try for free

side menu

Get Started

play_arrow

Learn more

play_arrow

Common use cases

play_arrow

Open a document

play_arrow

Save a document

play_arrow

Viewer

play_arrow

UI Customization

play_arrow

Annotations

play_arrow

Collaboration

play_arrow

Forms

play_arrow

Signature

play_arrow

Searching

play_arrow

Measurement

play_arrow

Compare

play_arrow

Advanced Capabilities

play_arrow

PDF.js Express REST API

play_arrow

Migration Guides

play_arrow

Real-time collaboration client

The following features are available in:

check

PDF.js Express Viewer

help_outline

PDF.js Express Viewer is a free viewer with limited capabilities compared to PDF.js Express Plus

check

PDF.js Express Plus

help_outline

PDF.js Express Plus is a commercial PDF SDK for viewing, annotating, signing, form filling and more

In realtime collaboration, a client will merely act as a listener or trigger for events upon data creation/modification/deletion updating the current user or sending updates to other users.

  1. Create a JavaScript file and name it main.js.
  2. Instantiate PDF.js Express Web Viewer on a DOM element. Initial document can be any PDF file.
WebViewer({
  path: "lib",
  initialDoc: "MY_INITIAL_DOC.pdf",
  documentId: "unique-id-for-this-document"
}, document.getElementById('viewer'))
  .then((instance) => {
    // do something...
  })
  1. Create an instance of the server we created in this guide.
const server = new Server();
  1. Bind a callback function to DocumentViewer.documentLoaded event.
WebViewer(...)
  .then(instance => {
    const { documentViewer } = instance.Core;

    documentViewer.on('documentLoaded', () => {
      // Code in later steps will be added 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.
let authorId = null;

server.bind('onAuthStateChanged', (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
    server.signInAnonymously();
  }
});
  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 PDF.js Express and annotations in PDF
  annotationManager.setCurrentUser(authorName);
  // Open popup for the returning author
  window.alert(`Welcome back ${authorName}`);
}

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

function updateAuthor(authorName) {
  // The author name will be used for both PDF.js Express and annotations in PDF
  annotationManager.setCurrentUser(authorName);
  // 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.
async 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.
  const [annotation] = await annotationManager.importAnnotCommand(data.val().xfdf);
  annotation.authorId = data.val().authorId;
  annotationManager.redrawAnnotation(annotation);
  myWebViewer.getInstance().fireEvent('updateAnnotationPermission', [annotation]);
}

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

 function onAnnotationDeleted(data) {
  // data.key would return annotationId since our server method is designed as
  // annotationsRef.child(annotationId).set(annotationData)
  const command = '<delete><id>' + data.key + '</id></delete>';
  annotationManager.importAnnotCommand(command).then(importedAnnotations => { });
}
  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.exportAnnotCommand. 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/CoreControls.AnnotationManager.html#importAnnotCommand] in server data callback functions.
annotationManager.addEventListener('annotationChanged', (annotations, type, { imported }) => {
  if (imported) {
    return;
  }
  annotations.forEach(annotation => {
    annotationManager.exportAnnotCommand().then(xfdf =>{
      if (type === 'add') {
            let parentAuthorId = null;
            if (annotation.InReplyTo) {
              parentAuthorId = annotationManager.getAnnotationById(annotation.InReplyTo).authorId || 'default';
            }
            server.createAnnotation(annotation.Id, {
              authorId: authorId,
              parentAuthorId: parentAuthorId,
              xfdf: xfdf
            });
          } else if (type === 'modify'){
            let parentAuthorId = null;
            if (annotation.InReplyTo) {
              parentAuthorId = annotationManager.getAnnotationById(annotation.InReplyTo).authorId || 'default';
            }
            server.updateAnnotation(annotation.Id, {
              authorId: authorId,
              parentAuthorId: parentAuthorId,
              xfdf: xfdf
            });
          } else if (type === 'delete') {
            server.deleteAnnotation(annotation.Id);
        }
    });
  });
});
  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((author, annotation) => annotation.authorId === authorId);