vue-pdf二次封装及解决无法显示中文问题

420 阅读1分钟

pdf.jpg

前言

vue-pdf 可以实现PDF文件在线预览并且支持分页。安装方式:npm install --save vue-pdf

完整代码

<template>
    <el-dialog :visible="visible" title="查看PDF" width="1100px" top="2vh" append-to-body @close="handleClose">
        <pdf-viewer 
            v-if="url" 
            style="height: 750px;overflow: auto;"
            :src="url"
            :page="pageData.currentPage"
            @num-pages="pageData.total = $event"
            @page-loaded="pageData.currentPage = $event"
            @loaded="loadPdfHandler()">
        </pdf-viewer>
        <div class="ui-pdf-page" v-if="pageData.total > 1">
            <span @click="changePdfPage(0)" :class="pageData.currentPage == 1 ? '' : 'ui-link'">上一页</span>
            <span>{{pageData.currentPage + '/' + pageData.total}}</span>
            <span @click="changePdfPage(1)" :class="pageData.currentPage == pageData.total ? '' : 'ui-link'">下一页</span>
        </div>
    </el-dialog>
</template>
<script>
    import pdfViewer from 'vue-pdf'
    import CMapReaderFactory from 'vue-pdf/src/CMapReaderFactory.js' //解决中文显示

    export default{
        components: {
            pdfViewer
        },
        name: 'ComPdfView',
        props: {
            src: {
                type: String,
                default: '',
            },
            visible: {
                type: Boolean,
                default: false
            },
        },
        data(){
            return {
                url: '',
                pageData: {
                    currentPage: 0,
                    total: 0,
                }
            }
        },
        watch:{
            visible(val) {
                if (val) {
                    this.url = pdfViewer.createLoadingTask({ url: this.src, CMapReaderFactory });
                }
            }
        },
        methods: {

            handleClose() {
                this.pageData.currentPage = 1;
                this.$emit('update:visible', false);
            },

            changePdfPage (val) {
                if (val === 0 && this.pageData.currentPage > 1) {
                    this.pageData.currentPage--
                }
                if (val === 1 && this.pageData.currentPage < this.pageData.total) {
                    this.pageData.currentPage++
                }
            },

            loadPdfHandler() {
                this.pageData.currentPage = 1;
            }
        }
    }
</script>
<style scoped lang="less">
    .ui-pdf-page span {
        font-size: 12px;
        padding: 0 20px;
        color: #626879;
    }
    .ui-pdf-page span.ui-link {
        color: #3c8cff;
        cursor: pointer;
    }
</style>

解决无法显示中文问题

关键代码

import pdfViewer from 'vue-pdf'
import CMapReaderFactory from 'vue-pdf/src/CMapReaderFactory.js'

this.url = pdfViewer.createLoadingTask({ url: this.src, CMapReaderFactory });