Sergio Garcia Heras
Sergio Garcia Heras

Reputation: 1

How to render a base64-encoded PDF in an iframe using PDF.js?

I am building a web app that needs to render a PDF from a Base64 string. I am using PDF.js to render the PDF in an iframe, but I am facing an issue where the document is not being displayed.

I first make an API call to retrieve the Base64 PDF string and store it in the sessionStorage when it's received:

useEffect(() => {
  if (base64Pdf) {
    // Store the base64 PDF in sessionStorage
    sessionStorage.setItem('pdfBase64', base64Pdf);
    
  }
}, [base64Pdf]);

return (
  <div>
    <iframe
      src="/pdfjs-dist/web/viewer.html"
      height="720"
      width="100%"
      style={{ borderWidth: '0px' }}
    />
  </div>
);

In the viewer.html file, I use the following script to get the Base64 PDF string from sessionStorage:

var DEFAULT_URL = '';
  var pdfUrl = document.location.search.substring(1);  // Get URL parameter

  if (null == pdfUrl || '' == pdfUrl) {
    var BASE64_MARKER = ';base64,';
    var pdfAsDataUri = sessionStorage.getItem('pdfBase64');  // Retrieve the base64 PDF from sessionStorage

    console.log('pdfAsDataUri content:', pdfAsDataUri);  // Debugging

    if (pdfAsDataUri && pdfAsDataUri.indexOf(BASE64_MARKER) === -1) {
      // If the base64 string does not have the marker, add the appropriate prefix for a PDF
      pdfAsDataUri = 'data:application/pdf;base64,' + pdfAsDataUri;
      console.log('Base64 string with marker added:', pdfAsDataUri);  // Debugging
    }

    if (pdfAsDataUri && pdfAsDataUri.indexOf(BASE64_MARKER) !== -1) {
      var pdfAsArray = convertDataURIToBinary(pdfAsDataUri);  // Convert base64 to binary
      DEFAULT_URL = pdfAsArray;  // Assign the binary array to DEFAULT_URL
      console.log('Generated binary array:', pdfAsArray);  // Debugging
    } else {
      console.error('Invalid base64 string or missing base64 marker');
    }

    function convertDataURIToBinary(dataURI) {
      var BASE64_MARKER = ';base64,';
      var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
      var base64String = dataURI.substring(base64Index);

      base64String = base64String.replace(/[\n\r]/g, '').trim();

      try {
        var raw = window.atob(base64String);  // Decode base64 string to binary
      } catch (error) {
        console.error('Error decoding base64:', error);
        return new Uint8Array();  // Return empty array in case of error
      }

      var rawLength = raw.length;
      var array = new Uint8Array(new ArrayBuffer(rawLength));
      for (var i = 0; i < rawLength; i++) {
        array[i] = raw.charCodeAt(i) & 0xff;  // Convert each byte to binary
      }
      return array;  // Return binary array
    }
  }

Upvotes: 0

Views: 68

Answers (0)

Related Questions