安装 :npm install pdfjs-dist
- <template>
- <div>
- <el-card ref="pdf" class="file-card" shadow="never" :body-style="{ padding: '0px' }" >
- <canvas v-for="page in numPages" :ref="'canvas' + page" :key="page"></canvas>
- </el-card>
- </div>
- </template>
-
- <script>
- import PDFJS from 'pdfjs-dist'
- export default {
- data () {
- return {
- pdfDoc: null,
- numPages: 0
- }
- },
- methods: {
- renderPage (num) {
- this.pdfDoc.getPage(num)
- .then((page) => {
- const canvas = this.$refs['canvas' + num][0]
- // const canvas = document.getElementById('canvas' + num)
- const ctx = canvas.getContext('2d')
- var viewport = page.getViewport({ scale: 2 })
- const viewportElem = document.querySelector('meta[name=viewport]')
- viewportElem.setAttribute('content', 'width=device-width')
- canvas.width = viewport.width // 画布大小,默认值是width:300px,height:150px
- canvas.height = viewport.height
- canvas.style.width = '100%' // 画布的框架大小
- const renderContext = {
- canvasContext: ctx,
- viewport: viewport
- }
- page.render(renderContext)
- if (this.numPages > num) {
- this.renderPage(num + 1)
- }
- })
- }
- },
- created () {
- const that = this
-
- PDFJS.disableWorker = true
- PDFJS.GlobalWorkerOptions.workerSrc = '/js/pdf.worker.js'
- PDFJS.getDocument({
- url: '地址',
- cMapUrl: 'https://unpkg.com/pdfjs-dist@2.0.943/cmaps/',
- cMapPacked: true
- }).promise.then((pdf) => {
- this.pdfDoc = pdf
- this.numPages = this.pdfDoc.numPages
- that.$nextTick(() => {
- that.loading = false
- that.renderPage(1)
- })
- })
- }
- }
- </script>
-
- <style lang="scss" scoped>
-
- .file-card{
- border: none;
- width:100%;
- height: 100%;
- overflow:auto;
- }
- </style>