vue-pdf-app
vue-pdf-app copied to clipboard
How to use ArrayBuffer as the value of "pdf" paramter?
trafficstars
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:
Am I getting the wrong ArrayBuffer? How do I pass the ArrayBuffer correctly to the PDFViwer?
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);