移动端H5使用pdf.js预览

发布时间 2023-10-27 15:15:00作者: Nancy*

1.下载pdf.js文件Getting Started (mozilla.github.io)

 

2.将下载的文件放进uniapp项目中

 3.创建预览页面

 代码:

<template>
    <view>
        <web-view :src="allUrl"></web-view>
    </view>
</template>

<script>
    import request from "@/utils/request.js";

    export default {
        data() {
            return {
                viewerUrl: '/static/web/viewer.html',
                allUrl: ''
            }
        },
        onLoad(e) {
            if (e.path.indexOf('http') == -1) {
                let fileUrl =
                    request.BASE_URL + '/sysFileInfo/public/preview?fileId=' + e.path.split('=')[1]
                console.log('fileUrl----', fileUrl, request.BASE_URL + '/sysFileInfo/public/preview?fileId=' + e.path
                    .split('=')[1])
                // let fileUrl = encodeURIComponent(
                //     "/static/web/compressed.tracemonkey-pldi-09.pdf")      
                this.allUrl = this.viewerUrl + '?file=' + fileUrl; // encodeURIComponent 函数可把字符串作为 URI 组件进行编码;
                console.log(this.allUrl)

            } else {
                console.log('e.path', e.path)
                this.allUrl = this.viewerUrl + '?file=' + encodeURIComponent(e.path)
                console.log(this.pdfUrl)
            }
        }
    }
</script>

最后附上预览效果: