Some test text!

Search
Hamburger Icon

Salesforce / Guides / Opening Documents

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 ContentVersion object allows for versioning of the ContentDocument which is linked to a Salesforce record via the ContentDocumentLink.

You can use the following Apex code snippet to pass the relevant ContentVersion record to your WebViewer instance:

ContentVersionController.cls

// force-app\main\default\classes\PDFTron_ContentVersionController.cls

//snipped for brevity
@AuraEnabled(Cacheable=true)
public static List<ContentVersionWrapper> getAttachments(String recordId){
  try {
    List<String> cdIdList = new List<String> ();
    List<ContentVersionWrapper> cvwList = new List<ContentVersionWrapper> ();

    //Find links between record & document
    for(ContentDocumentLink cdl : 
      [   SELECT id, ContentDocumentId, ContentDocument.LatestPublishedVersionId 
          FROM ContentDocumentLink 
          WHERE LinkedEntityId = :recordId    ]) {
            cdIdList.add(cdl.ContentDocumentId);
    }
    //Use links to get attachments
    for(ContentVersion cv : 
      [   SELECT Id, Title,FileExtension, VersionData 
          FROM ContentVersion 
          WHERE ContentDocumentId IN :cdIdList 
          AND IsLatest = true ]) {
            cvwList.add(new ContentVersionWrapper(cv));    
      }
      
      return cvwList;
    } catch (Exception e) {
            throw new AuraHandledException(e.getMessage());
    }
}

//sample wrapper class
public class ContentVersionWrapper {
  @AuraEnabled
  public String name {get; set;}
  @AuraEnabled
  public String body {get; set;}
        
  public ContentVersionWrapper(ContentVersion contentVer) {
    this.name = contentVer.Title + '.' + contentVer.FileExtension;
    this.body = EncodingUtil.base64Encode(contentVer.VersionData);
  }
}

Converting a base64 string to blob inside your WebViewer LWC

function _base64ToArrayBuffer(base64) {
  var binary_string =  window.atob(base64);
  var len = binary_string.length;
  var bytes = new Uint8Array( len );
  for (var i = 0; i < len; i++)        {
      bytes[i] = binary_string.charCodeAt(i);
  }
  return bytes.buffer;
}

Then you can use the function to build your blob and pass it to WebViewer like so:

//snipped for brevity
import { registerListener, unregisterAllListeners } from 'c/pubsub';

connectedCallback() {
  registerListener('blobSelected', this.handleBlobSelected, this);
  //register other listeners here
}

disconnectedCallback() {
  //unregister all listeners here
}

handleBlobSelected(record) {
  record = JSON.parse(record);

  let blobby = new Blob([_base64ToArrayBuffer(record.body)], {
    type: mimeTypes[record.FileExtension]
  });

  const payload = {
    blob: blobby,
    extension: record.cv.FileExtension,
    filename: record.cv.Title + "." + record.cv.FileExtension,
    documentId: record.cv.Id
  };
    this.iframeWindow.postMessage({type: 'OPEN_DOCUMENT_BLOB', payload} , '*');
  }

config_apex.js

You can use

//snipped for brevity
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;
        instance.loadDocument(blob, { extension, filename, documentId })
        break;
      default:
        break;
    }
  }
}
//snipped for brevity
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 })
        break;
      default:
        break;
    }
  }
}

Code sample

You can find a full code sample that implements opening documents in Salesforce on our Github repository.

Get the answers you need: Chat with us