0

I am trying to use pdf.js to render a base64 representation of a pdf. My component is as follows :

<template>
    <div class="wrapper">
        <iframe src="/resource/pdfjs/web/viewer.html" onload={onLoad} width="800"></iframe>
    </div>
</template> 

controller :

import { LightningElement, api } from 'lwc';

export default class Pdfreader extends LightningElement {
    @api pdfData;
    onLoad() {
        let pdfString = 'JVBERi0xLjAKMSAwIG9iajw8L1BhZ2VzIDIgMCBSPj5lbmRvYmogMiAwIG9iajw8L0tpZHNbMyAw\nIFJdL0NvdW50IDE+PmVuZG9iaiAzIDAgb2JqPDwvTWVkaWFCb3hbMCAwIDMgM10+PmVuZG9iagp0\ncmFpbGVyPDwvUm9vdCAxIDAgUj4+Cg=='
        this.template
            .querySelector("iframe")
            .contentWindow.postMessage(pdfString,  window.location.origin);
    }
}

This component on load displays the default PDF in the iframe instead of displaying the PDF string provided :

enter image description here

1 Answer 1

1

You'll need to implement your own handler to get postMessage to work.

<script>
  if (window.addEventListener) {
    window.addEventListener("message", handleMessage, false);
  }else{
    window.attachEvent("onmessage", handleMessage);
  }

  function handleMessage(evt){
    let raw = atob(evt.data);
    let uint8Array = new Uint8Array(raw.length);
    for (let i = 0; i < raw.length; i++) {
      uint8Array[i] = raw.charCodeAt(i);
    }
    PDFViewerApplication.open(uint8Array);
  }
</script>

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .