記録:vuecli 3+pdfjs-dist簡単なpdfプレビューを実現
13170 ワード
vue + pdfjs-dist
1、インストール依存
npm install pdfjs-dist -S
2、プロジェクトの使用
<template>
<div class="pdf-container" v-if="showPdf">
<canvas v-for="page in pages" :id="'canvas' + page" :key="page">canvas>
div>
template>
<script>
import PDF from 'pdfjs-dist'
PDF.disableWorker = true
export default {
name: '',
data () {
return {
width: 100,
pdfDoc: null,
pages: 0
}
},
methods: {
/*
* PDF
* url: pdf public/pdf (test.pdf)
* this.loadFile(url)
* */
loadFile (url) {
PDF.getDocument(url)
.then((pdf) => {
this.pdfDoc = pdf
this.pages = this.pdfDoc.numPages
this.$nextTick(() => {
this.renderPage(1)
})
})
},
/*
* PDF
* */
renderPage (num) {
this.pdfDoc.getPage(num)
.then((page) => {
let canvas = document.getElementById('canvas' + num)
let ctx = canvas.getContext('2d')
let dpr = window.devicePixelRatio || 1 //
let bsr = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1 // canvas , img
let ratio = dpr / bsr
let viewport = page.getViewport(1.5)
canvas.width = viewport.width * ratio // , width:300px,height:150px
canvas.height = viewport.height * ratio
canvas.style.width = viewport.width + 'px' //
canvas.style.height = viewport.height + 'px'
let renderContext = {
canvasContext: ctx,
viewport: viewport
}
page.render(renderContext)
if (this.pages > num) {
this.renderPage(num + 1)
} else {
this.closeServerLoadingHandle()
}
})
}
}
}
</script>