實現pdf在線預覽 需求是不能另存為pdf(若使用iframe直接嵌入瀏覽器可以隨意另存為)
這樣實現后把用戶的右鍵、F12禁止即可
//html
<div class="pdf-box"> <canvas v-for="i in pageCount" :key="i" class="myCanvas"></canvas> </div>
//JS npm i pdfjs-dist@2.0.943(我的pdfjs版本)
import pdfJS from "pdfjs-dist/webpack.js"; export default { name: "PDFViewer", props: { src: { type: String, default: null } }, data() { return { pageCount: 0 // 總頁數 }; }, created() {}, mounted() { this.init(); }, methods: { // 初始化pdf init() { pdfJS.getDocument(this.src).promise.then(pdfDoc => { this.pageCount = pdfDoc.numPages; this.renderPage(pdfDoc); }); }, async renderPage(pdfDoc) { let canvas; await this.$nextTick(() => { canvas = document.querySelectorAll(".myCanvas"); }); // U console.log(canvas); canvas.forEach((item, index) => { pdfDoc.getPage(index + 1).then(page => { let viewport = page.getViewport(1); //得到一個頁面 item.height = viewport.height; item.width = viewport.width; console.log(viewport, item); let ctx = item.getContext("2d"); var renderContext = { canvasContext: ctx, //畫布 viewport: viewport //內容 }; page.render(renderContext); }); }); } } };
注意:引入pdfjs 要引入打包完成的webpack.js文件 不能直接引用
