关于pdf:pdfjsdist模块实现pdf文件预览功能

37次阅读

共计 1530 个字符,预计需要花费 4 分钟才能阅读完成。

对于 pdf 文件,通过测试 ios 是能够失常关上,而在安卓机上,则须要下载福昕阅读器能力关上。如何可能不借助客户端之力,依附 h5 来实现 pdf 文件预览性能呢?咱们能够装置 pdfjs-dist 模块来实现。

本示例是基于 vue 框架:

  1. 装置 pdfjs-dist 包:

    npm install pdfjs-dist -D

    这里应用的版本是:"pdfjs-dist": "^2.4.456"

2、html 模板

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

3、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: []
        };
    },
    created() {this._loadFile(yourUrl);
    },
    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) {this.$showLoading();
            PDFJS.getDocument(url).promise.then((pdf) => {this.$closeLoading();
                this.pdfDoc = pdf
                this.pages = this.pdfDoc.numPages
                this.$nextTick(() => {this._renderPage(1);
                });
            });
        }
    }
};

4、css 代码

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

正文完
 0