Section:

Convert documents in Salesforce

Getting Started

We recommend the Overview page to learn how to correctly use a config.js before getting started with using Webviewer.

Convert an Open Document

To convert a document, first you'll need to open a document in our lightning web componenet where the Webviewer is mounted in an iFrame (in our sample, it is pdftronWvInstance).

Once a document is loaded and viewable in our preview screen, you'll be allowed to convert documents in our available formats:

  • PDF, PDF/A
  • DOCX, XLSX, PPTX (MS Office software or licenses are not required)
  • JPG, PNG, TIFF

We store the open document into an object and label it as payload. Storing the neccessary information for conversion and saving the converted file onto salesforce.

JavaScript

1handleBlobSelected(record) {
2 const blobby = new Blob([_base64ToArrayBuffer(record.body)], {
3 type: mimeTypes[record.FileExtension]
4 });
5 const payload = {
6 blob: blobby,
7 extension: record.cv.FileExtension,
8 file: record.cv.Title,
9 filename: record.cv.Title + "." + record.cv.FileExtension,
10 documentId: record.cv.Id
11 };
12
13 this.payload = {...payload};
14 this.iframeWindow.postMessage({ type: 'OPEN_DOCUMENT_BLOB', payload }, '*');
15 }

Convert in your config.js

Since WebViewer is hosted in an iFrame, we need to use our config.js file to access our WebViewer instance. You need to post a message to your iframeWindow like so:

JavaScript

1this.iframeWindow.postMessage({type: 'CONVERT DOCUMENT', payload }, '*');

In a Salesforce deployment, the equivalent of instance is readerControl.

Standard conversion to pdf

In your config.js file, you can you listen for messages posted to the iFrame by registering an event listener using window.addEventListener("message", this.handleReceiveMessage). In this case, handleReceiveMessage is a function that handles these posted messages. You can review the snippet below for an example of how to deal with posted messages.

This snippet uses the instance of Webviewer and converts the loaded document as a PDF. When downloaded, we are allowed to download from the instance using our API call downloadPdf(). Writing to Salesforce we have to grab file data and return the converted data back to the lwc with a event listener.

JavaScript

1async function toPdf (payload, transport) {
2 if (transport){
3 const doc = instance.Core.documentViewer.getDocument();
4 const buffer = await doc.getFileData({ downloadType: payload.exportType });
5 const bufferFile = new Uint8Array(buffer);
6
7 saveFile(bufferFile, payload.file, "." + payload.exportType);
8
9 } else {
10 let file = payload.file;
11
12 parent.postMessage({ type: 'DOWNLOAD_DOCUMENT', file }, '*');
13 instance.downloadPdf({filename: payload.file});
14 }
15}

JavaScript

1handleReceiveMessage = (event) => {
2 const me = this;
3 if (event.isTrusted && typeof event.data === 'object') {
4 switch (event.data.type) {
5 case 'SAVE_DOCUMENT':
6 const cvId = event.data.payload.contentDocumentId;
7 saveDocument({ json: JSON.stringify(event.data.payload), recordId: this.recordId ? this.recordId : '', cvId: cvId })
8 .then((response) => {
9 me.iframeWindow.postMessage({ type: 'DOCUMENT_SAVED', response }, '*');
10
11 fireEvent(this.pageRef, 'refreshOnSave', response);
12
13 fireEvent(this.pageRef, 'finishConvert', '');
14 this.showNotification('Success', event.data.payload.filename + ' Saved', 'success');
15 })
16 .catch(error => {
17 me.iframeWindow.postMessage({ type: 'DOCUMENT_SAVED', error }, '*')
18 fireEvent(this.pageRef, 'refreshOnSave', error);
19 console.error(event.data.payload.contentDocumentId);
20 console.error(JSON.stringify(error));
21 this.showNotification('Error', error.body, 'error');
22 });
23 break;
24 case 'DOWNLOAD_DOCUMENT':
25 const body = event.data.file + ' Downloaded';
26 fireEvent(this.pageRef, 'finishConvert', '');
27 this.showNotification('Success', body, 'success');
28 break;
29 default:
30 break;
31 }
32 }
33 }

Conversion to image files

Similar to standard conversion to pdf, all conversions including pdf to image files would converted in config.js file.

The following snippet uses multiple namespaces in our API:

JavaScript

1const pdfToImage = async (payload, transport) => {
2
3 await PDFNet.initialize();
4
5 let doc = null;
6
7 await PDFNet.runWithCleanup(async () => {
8
9 const buffer = await payload.blob.arrayBuffer();
10 doc = await PDFNet.PDFDoc.createFromBuffer(buffer);
11 doc.initSecurityHandler();
12 doc.lock();
13
14 const count = await doc.getPageCount();
15 const pdfdraw = await PDFNet.PDFDraw.create(92);
16
17 let itr;
18 let currPage;
19 let bufferFile;
20
21 // Handle multiple pages
22 for (let i = 1; i <= count; i++){
23
24 itr = await doc.getPageIterator(i);
25 currPage = await itr.current();
26 bufferFile = await pdfdraw.exportStream(currPage, payload.exportType.toUpperCase());
27 transport ? saveFile(bufferFile, payload.file, "." + payload.exportType) : downloadFile(bufferFile, payload.file, "." + payload.exportType);
28
29 }
30
31 });
32
33}

Sample project

You can review the Salesforce PDF App to showcase an end-to-end example of document conversion in Github repository.

Live demo

Check out this live file conversion demo (hosted outside of Salesforce).

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales