如何在vue项目里面展示 pdf文件

首先下载  pdfjs-dist 这个插件

在然后在 component 里面添加一个 空白的.vue文件

复制下面的代码

注意:url 是在public 里面的 静态资源  

访问 public 里面的 资源 不需要跨域

<template>
     <div class="canvas-container">
        <canvas v-for="page in pages" :id="'the-canvas'+page" :key="page">
        </canvas>
    </div>
</template>

<script>
import PDFJS from 'pdfjs-dist';
import workerSrc from 'pdfjs-dist/build/pdf.worker.entry'
PDFJS.workerSrc = workerSrc;

export default {
    name: 'Pdf',
    data() {
        return {
            pages: []
        };
    },
    // props:{
    //     str:String,
    // },
    created() {
        let url = "/report.pdf"
       this._loadFile(url);
    },
    methods: {
        _renderPage (num) {
            this.pdfDoc.getPage(num).then((page) => {
                let canvas = document.getElementById('the-canvas' + num)
                var vp = page.getViewport({scale: 1});
                let ctx = canvas.getContext('2d')
                let dpr = window.devicePixelRatio || 1
                let bsr = ctx.webkitBackingStorePixelRatio ||
                    ctx.mozBackingStorePixelRatio ||
                    ctx.msBackingStorePixelRatio ||
                    ctx.oBackingStorePixelRatio ||
                    ctx.backingStorePixelRatio || 1
                let ratio = dpr / bsr
                let viewport = page.getViewport({scale: window.innerWidth / vp.width});
                canvas.width = viewport.width * ratio
                canvas.height = viewport.height * ratio
                canvas.style.width = viewport.width + '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)
                }
            })
        },
        _loadFile (url) {
            PDFJS.getDocument(url).promise.then((pdf) => {
                this.pdfDoc = pdf
                this.pages = this.pdfDoc.numPages
                this.$nextTick(() => {
                    this._renderPage(1);
                });
            });
        }
    }
};

</script>

<style lang="scss" scoped>
.canvas-container{
    margin: 0 auto;
    canvas{
        height: 100vh;
    }
}
</style>

 

上一篇:控制容器的宽高比---aspect-ratio


下一篇:地表建筑物识别-异常数据的清洗