[SalesForce] Preview attached pdf/doc files in lightning component

I have a requirement wherein i need to display uploaded files as preview in a lightning component. I have tried it with the below code but was unsuccessfull:
Lightning Component:

<aura:component controller="DocPreview" access="global">
<aura:handler name="init" action="{!c.doInit}" value="{!this}"/>

 <iframe src="" aura:id="preview" height="500px" width="500px"></iframe> 

</aura:component>

Lightning Helper:

var preview = component.find("preview");
var file = new File([result], "test");
var myURL= URL.createObjectURL(file);
preview.src =  myURL;

Here result is the Blob returned from the below code:
Apex Class:

List<Id> cdLst = new List<Id>();
for(ContentDocumentLink cdLnk : [SELECT ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId = :parentId])
    cdLst.add(cdLnk.ContentDocumentId);
cvLst = [SELECT VersionData FROM ContentVersion WHERE ContentDocumentId IN :(cdLst) LIMIT 25];

Blob cvData = (Blob)cvLst[0].VersionData;
return EncodingUtil.base64Encode(cvData);

Currently in the iframe below is displayed:

enter image description here

Any help would be highly appreciated.

Best Answer

Borrowed from this answer, you should be able to do something like the following:

var url = 'data:application/pdf;base64,' + result;
fetch(url)
    .then(res => res.blob())
    .then($A.getCallback(blob => component.find("preview").src = URL.createObjectURL(new File([blob], 'preview.pdf', { type: 'application/pdf' }))));

Your main problem is that the content you're getting back from the Apex code is bae64 encoded. We need to reverse this encoding to get the binary data back out. Traditionally, we would have used atob, but that method shouldn't be used. Instead, we can use fetch to decode the base64 data back in to a blob, and from there create the File, and finally the Object URL.