> For the complete documentation index, see [llms.txt](https://docs.apryse.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.apryse.com/web/get-started/samples/webviewer-salesforce.md).

# Implement WebViewer in Salesforce as a Lightning Web Component

Integrating Apryse WebViewer in Salesforce as a Lightning Web Component. Note that Salesforce static resources have file size limitation to 5MB, to safely upload to the Salesforce platform.

This sample is demonstrating how to integrate the Apryse WebViewer into Salesforce as a Lightning Web Component. For more information, see this [guide](https://github.com/iKettles/apryse-gitbook/tree/main/salesforce/guides.md).

WebViewer provides a slick out-of-the-box responsive UI that enables you to view, annotate and manipulate PDFs and other document types inside any web project.

Once you generate your license key, it will automatically be included in your sample code below.

{% @apryse-license-key/apryse-license-key platform="WEB\_VIEWER" variant="compact" %}

Click the button below to view the full project in GitHub.

{% tabs %}
{% tab title="apryseWvInstance.js" %}

<pre class="language-js" data-line-numbers><code class="lang-js">import getUser from '@salesforce/apex/Apryse_ContentVersionController.getUser';
import saveDocument from '@salesforce/apex/Apryse_ContentVersionController.saveDocument';
import libUrl from '@salesforce/resourceUrl/lib';
import myfilesUrl from '@salesforce/resourceUrl/myfiles';
import { fireEvent, registerListener, unregisterAllListeners } from 'c/pubsub';
import { CurrentPageReference } from 'lightning/navigation';
import { loadScript } from 'lightning/platformResourceLoader';
import { api, LightningElement, wire } from 'lwc';
import mimeTypes from './mimeTypes';

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

export default class ApryseWvInstance extends LightningElement {
  //initialization options
  fullAPI = true;
  enableRedaction = true;
  enableFilePicker = true;

  uiInitialized = false;

  source = 'My file';
  @api recordId;

  @wire(CurrentPageReference)
  pageRef;

  username;

  connectedCallback() {
    registerListener('blobSelected', this.handleBlobSelected, this);
    registerListener('closeDocument', this.closeDocument, this);
    registerListener('downloadDocument', this.downloadDocument, this);
    registerListener('fileSelected', this.handleFileSelected, this);
    window.addEventListener('message', this.handleReceiveMessage.bind(this), false);
  }

  disconnectedCallback() {
    unregisterAllListeners(this);
    window.removeEventListener('message', this.handleReceiveMessage);
  }

  handleBlobSelected(record) {
    const 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 }, '*');
  }

  renderedCallback() {
    var self = this;

    if (this.uiInitialized) { 
        return;
    }

    Promise.all([
        loadScript(self, libUrl + '/webviewer.min.js')
    ])
    .then(() => this.handleInitWithCurrentUser())
    .catch(console.error);
  }

  handleFileSelected(file) {
    this.iframeWindow.postMessage({type: 'OPEN_DOCUMENT', file: file}, '*')
  }

  handleInitWithCurrentUser() {
    getUser()
    .then((result) => {
        this.username = result;
        this.error = undefined;

        this.initUI();
    })
    .catch((error) => {
      console.error(error);
      this.showNotification('Error', error.body.message, 'error');
    });
  }

  initUI() {
    var myObj = {
      libUrl: libUrl,
      fullAPI: this.fullAPI || false,
      namespacePrefix: '',
      username: this.username,
    };
    var url = myfilesUrl + '/webviewer-demo-annotated.pdf';

    const viewerElement = this.template.querySelector('div')
    // eslint-disable-next-line no-unused-vars
    const viewer = new WebViewer.Iframe({
      path: libUrl, // path to the Apryse 'lib' folder on your server
      custom: JSON.stringify(myObj),
      backendType: 'ems',
      config: myfilesUrl + '/config_apex.js',
      fullAPI: this.fullAPI,
      enableFilePicker: this.enableFilePicker,
      enableRedaction: this.enableRedaction,
      enableMeasurement: this.enableMeasurement,
      enableOptimizedWorkers: true,
      loadAsPDF: true,
      // l: '<code class="expression">visitor.claims.wvKey || "YOUR_LICENSE_KEY"</code>',
      // To use spreadsheet editor feature, uncomment the below line and comment out loadAsPDF: true
      // initialMode: WebViewer.Modes.SPREADSHEET_EDITOR,
    }, viewerElement);

    viewerElement.addEventListener('ready', () => {
      this.iframeWindow = viewerElement.querySelector('iframe').contentWindow;
    })

  }

  handleReceiveMessage(event) {
    const me = this;
    if (event.isTrusted &#x26;&#x26; typeof event.data === 'object') {
      switch (event.data.type) {
        case 'SAVE_DOCUMENT':
          const cvId = event.data.payload.contentDocumentId;
          saveDocument({ json: JSON.stringify(event.data.payload), recordId: this.recordId ? this.recordId : '', cvId: cvId })
          .then((response) => {
            me.iframeWindow.postMessage({ type: 'DOCUMENT_SAVED', response }, '*')
            fireEvent(this.pageRef, 'refreshOnSave', response);
          })
          .catch(error => {
            me.iframeWindow.postMessage({ type: 'DOCUMENT_SAVED', error }, '*')
            fireEvent(this.pageRef, 'refreshOnSave', error);
            console.error(event.data.payload.contentDocumentId);
            console.error(JSON.stringify(error));
            this.showNotification('Error', error.body, 'error')
          });
          break;
        default:
          break;
      }
    }
  }

  downloadDocument() {
    this.iframeWindow.postMessage({type: 'DOWNLOAD_DOCUMENT' }, '*')
  }

  @api
  closeDocument() {
    this.iframeWindow.postMessage({type: 'CLOSE_DOCUMENT' }, '*')
  }
}
</code></pre>

{% endtab %}

{% tab title="visualforce-page-viewing.js" %}
{% code title="visualforce-page-viewing.js" lineNumbers="true" %}

```js
function initWebViewer(options) {
  console.log(options);

  var myObj = {
    libUrl: options.lib,
    fullAPI: true,
    namespacePrefix: '',
  };
  var resourceConfig = options.myfiles + '/config.js';

  WebViewer(
    {
      path: options.lib,
      custom: JSON.stringify(myObj),
      config: resourceConfig,
      fullAPI: myObj.fullAPI,
      // initialDoc: 'https://pdftron.s3.amazonaws.com/downloads/pl/demo-annotated.pdf',
    },
    document.getElementById('viewer')
  ).then(instance => {
    console.log(instance);
    instance.loadDocument('https://pdftron.s3.amazonaws.com/downloads/pl/demo-annotated.pdf')
    // Use WebViewer API here
  })
}

```

{% endcode %}
{% endtab %}
{% endtabs %}

[View the full sample on GitHub](https://github.com/ApryseSDK/webviewer-samples/tree/main/webviewer-salesforce)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.apryse.com/web/get-started/samples/webviewer-salesforce.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
