sandanat / vue-pdf-app

VUEjs v2 PDF viewer based on Mozilla's PDFJS
MIT License
225 stars 103 forks source link

How to use ArrayBuffer as the value of "pdf" paramter? #112

Open yifengwang66 opened 1 year ago

yifengwang66 commented 1 year ago

I'm using Vue3 composition API and I get the PDF streaming data from fetch API. By doing below I hope the PDFViwer will segmented display the PDF.

<template>
    <VuePdfApp :pdf="PDFBuffer"></VuePdfApp>
</template>
<script setup>
const PDFBuffer = ref(null);
function getPDFStream(url) {
  fetch(url).then((response) => {
    const reader = response.body.getReader();
    const decoder = new TextDecoder("utf-8");
    let buffer = "";
    function processStreamResult(result) {
      console.log("result", result);
      const chunk = decoder.decode(result.value, {
        stream: !result.done,
      });
      buffer += chunk;
      console.log("buffer", buffer);
      PDFBuffer.value = concatArrayBuffers(PDFBuffer.value, result.value);
      console.log("PDFBuffer", PDFBuffer.value);

      if (!result.done) {
        return reader.read().then(processStreamResult);
      } else {
        reader.releaseLock();
      }
    }
    return reader.read().then(processStreamResult);
  });
}
</script> 

But, it doesn't work, I got a error like this: image Am I getting the wrong ArrayBuffer? How do I pass the ArrayBuffer correctly to the PDFViwer?

maxrks commented 10 months ago

Server side: In API controller, do read pdf or generate pdf as buffer, change buffer to base64 string with buffer.toString('base64').

Client side: Make a post to the server side controller, get the post-back base64 string, change it to arraybuffer, pass the arraybuffer result to the pdf property.

Try this to change base64 to arraybuffer

function base64ToArrayBuffer(base64) {
    var binaryString = atob(base64);
    var bytes = new Uint8Array(binaryString.length);
    for (var i = 0; i < binaryString.length; i++) {
      bytes[i] = binaryString.charCodeAt(i);
    }
    return bytes.buffer;
  }

or

import { decode } from "base64-arraybuffer";
const buffer = decode(base64String);