vue框架实现pdf在线预览
生活随笔
收集整理的這篇文章主要介紹了
vue框架实现pdf在线预览
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
記錄下實現pdf預覽展示的坑,剛開始使用vue-pdf在本地運行是可以展示的,但是發布測試環境展示不出來
報以下錯誤:
網上找的的是:
網上搜到的解決方法
但是我看半天不知道怎么解決,然后換pdfjs-dist插件
安裝
npm install pdfjs-dist --save引入
import PDFJS from "pdfjs-dist"; console.log(PDFJS) //undefined打印PDFJS返回undefiend
解決辦法
刪掉前面一個小尖括號,就能安裝指定的依賴包了,然后項目就能正常運行了。
打印PDFJS返回一個對象
實現代碼
<template><div><canvas v-for="page in pages" :id="'the-canvas'+page" :key="page"></canvas></div> </template> <script> import PDFJS from "pdfjs-dist" export default {data() {return {pdfUrl: './pdf/demo.pdf',pdfDoc: null,pages: 0,}},created() {this.loadFile(this.pdfUrl)},methods: {loadFile (url) {PDFJS.getDocument(url).then((pdf) => {this.pdfDoc = pdfthis.pages = this.pdfDoc.numPagesthis.$nextTick(() => {this.renderPage(1)})})},renderPage (num) {this.pdfDoc.getPage(num).then((page) => {let canvas = document.getElementById('the-canvas' + num)let ctx = canvas.getContext('2d')let dpr = window.devicePixelRatio || 1let bsr = ctx.webkitBackingStorePixelRatio ||ctx.mozBackingStorePixelRatio ||ctx.msBackingStorePixelRatio ||ctx.oBackingStorePixelRatio ||ctx.backingStorePixelRatio || 1let ratio = dpr / bsrlet viewport = page.getViewport(screen.availWidth / page.getViewport(1).width)canvas.width = viewport.width * ratiocanvas.height = viewport.height * ratiocanvas.style.width = viewport.width + 'px'canvas.style.height = viewport.height + 'px'ctx.setTransform(ratio, 0, 0, ratio, 0, 0)let renderContext = {canvasContext: ctx,viewport: viewport}page.render(renderContext)if (this.pages > num) {this.renderPage(num + 1)}})}} } </script><style lang="less" scoped> canvas {display: block; } </style>總結
以上是生活随笔為你收集整理的vue框架实现pdf在线预览的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 'React/RCTBridgeDele
- 下一篇: vue 对象里面放数组刷新问题_Vue