I must clarify that I am restricted from using any vue libraries to preview PDFs; only pure pdf.js and vue 3 are permitted.
- Utilizing
pdf.js
for presenting PDF files within myvue 3
project. - Inquiring about the ideal folder structure for the project to ensure functionality.
- Currently relying on a
cdnjs
link forpdf.js
; looking to switch to the distribution folder instead.
View distribution folder here
Planning to replace the usage of cdnjs
link with the distribution folder mentioned above.
- Showcasing my current implementation along with examples provided on the official website of pdf.js.
pdf-view.vue
<template>
<canvas :id="`the-canvas${index}`" style="border: 1px solid"></canvas>
</template>
<script setup>
import { onMounted, defineProps } from 'vue'
const { file, index } = defineProps(['file', 'index'])
onMounted(() => {
import('https://cdnjs.cloudflare.com/ajax/libs/pdf.js/4.0.379/pdf.mjs').then((pdfjsLib) => {
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/4.0.379/pdf.worker.min.mjs'
if (!file) return
const fileReader = new FileReader()
fileReader.onload = () => {
const array = new Uint8Array(fileReader.result)
const loadingTask = pdfjsLib.getDocument(array)
loadingTask.promise.then(
(pdf) => {
const pageNumber = 1
pdf.getPage(pageNumber).then((page) => {
const scale = 1.5
const viewport = page.getViewport({ scale })
const canvas = document.getElementById(`the-canvas${index}`)
const context = canvas.getContext('2d')
canvas.height = viewport.height
canvas.width = viewport.width
// Render PDF page into canvas context
const renderContext = {
canvasContext: context,
viewport: viewport
}
page.render(renderContext)
})
},
(reason) => {
// PDF loading error
console.error(reason)
}
)
}
fileReader.readAsArrayBuffer(file)
})
})
</script>
<style>
</style>
parent.vue
<template v-for="(file, index) in pdfFiles" :key="file">
<pdfview :file="file.file" :index="index" />
</template>
<script setup>
import pdfview from '@/components/pdf-view/pdf-view.vue'
</script>
Current directory setup
--Project
-public
-src
--components
---pdf-view
----pdf-view.vue [component]
---views
----parent.vue [component]