Some test text!

menu

Open a document

There are a few ways to open a document such as from a URL, a blob, the filesystem, or base64 data. Additionally, there are loading options to help WebViewer determine the type of the file being loaded.

Opening a document from the Salesforce Database

If you have a document uploaded into your instance of Salesforce, it will have a record in the database in the ContentVersion table.

The following SOQL query:

SELECT id,
  FileType,
  Title,
  FileExtension,
  Versiondata
FROM
  ContentVersion
WHERE
  islatest=true

Can be executed in the Developer Console, under the Query Editor tab.

The results of the query will help you find the ContentVersion.id needed as a parameter for the openFile function demonstrated in the following code snippet:

linkContentVersionController.cls

// force-app\main\default\classes\ContentVersionController.cls
public with sharing class ContentVersionController {
    // Snipped for brevity

    @RemoteAction
    @AuraEnabled(Cacheable=true)
    public static Map<String,String> getFileBlobById(String Id) {
        ContentVersion cv = [SELECT Id, Title, FileExtension, IsMajorVersion, IsLatest, VersionData, IsAssetEnabled FROM ContentVersion WHERE Id = :Id];
        // Returns string
        Map<String,String> response = new Map<String, String>();
        response.put('Title', cv.Title);
        response.put('FileExtension', cv.FileExtension);
        response.put('Content', EncodingUtil.base64Encode(cv.VersionData));

        return response;
    }

    // Snipped for brevity
}

linkWebViewer.js

import { LightningElement, wire, track, api } from 'lwc';
import { CurrentPageReference } from 'lightning/navigation';
/** ContentVersionController.getFileBlobById(id) Apex method */
import getFileBlobById from '@salesforce/apex/ContentVersionController.getFileBlobById';

export default class WvInstance extends LightningElement {
  // Snipped for brevity
  initUI() {
    const viewer = new PDFTron.WebViewer({
      // Snipped for brevity
    }, viewerElement);

    viewerElement.addEventListener('ready', () => {
      this.iframeWindow = viewerElement.querySelector('iframe').contentWindow;
      /**
       * @todo Replace CONTENT_VERSION_ID with the id stored in the Salesforce
       * database in the ContentVersion table
       */
      this.openFile('CONTENT_VERSION_ID')
    });
  }

  // Snipped for brevity
  /**
   * Given a ContentVersion.Id stored in the Salesforce database, the
   * Base64-encoded file is converted into a Blob, and opened in WebViewer
   *
   * @param {Number} Id A number that represents the ContentVersion.Id column
   * stored in the Salesforce database, pertaining to the file that will be
   * rendered by WebViewer
   */
  openFile(Id) {
    getFileBlobById({ Id }).then(response => {
      const  { Title, FileExtension, Content } = response
      const filename = `${Title}.${FileExtension}`;
      /**
       * Converts Base64-encoded binary data into a Blob
       *
       * @param {Base64} base64 The document in Base64 format, to be converted
       * to Blob
       * @returns {Blob} The content converted into a Blob
       */
      function base64ToBlob(base64) {
        const binaryString = window.atob(base64);
        const len = binaryString.length;
        const bytes = new Uint8Array(len);
        for (let i = 0; i < len; ++i) {
          bytes[i] = binaryString.charCodeAt(i);
        }
      
        return new Blob([bytes], { type: 'application/pdf' });
      };
      const blob = base64ToBlob(Content);
      const payload = {
        blob: blob,
        filename: filename,
        extension: FileExtension,
        documentId: this.contentVersionId,
      };
      this.iframeWindow.postMessage({type: 'OPEN_DOCUMENT_BLOB', payload }, '*');
    })
    .catch(this.showErrorMessage);
  }

  // Snipped for brevity
}

Take note of the @todo to replace 'CONTENT_VERSION_ID' when this.openFile is invoked

linkconfig.js

// ...

window.addEventListener("message", receiveMessage, false);

function receiveMessage(event) {
  if (event.isTrusted && typeof event.data === 'object') {
    switch (event.data.type) {
      // ...
      case 'OPEN_DOCUMENT_BLOB':
        const { blob, extension, filename, documentId } = event.data.payload;
        event.target.readerControl.loadDocument(
          blob,
          {
            extension,
            filename,
            documentId,
            officeOptions: {
              disableBrowserFontSubstitution: true,
            },
          },
        );
        break;
      case 'CLOSE_DOCUMENT':
        event.target.readerControl.closeDocument()
        break;
      default:
        break;
    }
  }
}

You can also find the full source code for LWC app with WebViewer here on this Github repository

Get the answers you need: Support

close

Free Trial

Get unlimited trial usage of PDFTron SDK to bring accurate, reliable, and fast document processing capabilities to any application or workflow.

Select a platform to get started with your free trial.

Unlimited usage. No email address required.

Join our live demo to learn about use cases & capabilities for WebViewer

Learn more
close