美文网首页
uniapp使用pdf.js(base64)

uniapp使用pdf.js(base64)

作者: 超开心儿 | 来源:发表于2021-08-05 14:48 被阅读0次

    一、下载pdf.js,按照如图结构放到项目根目录

    我下载的是Prebuilt (for older browsers) --> stable(v2.9)版本


    image.png

    二、新建一个web-view页面

    web-view 是一个 web 浏览器组件,可以用来承载网页的容器,会自动铺满整个页面

    <template>
        <view>
            <web-view :src="allUrl"></web-view>
        </view>
    </template>
    
    <script>
        export default {
            data() {
                return {
                    viewerUrl: '/hybrid/html/web/viewer.html',
                    allUrl: ''
                }
            },
            onLoad(options) {
                let pdf = `data:application/pdf;base64,${options.url}`;
                pdf = this.base64ToBlob(pdf)
                this.allUrl = this.viewerUrl + '?file=' + URL.createObjectURL(pdf)
            },
            methods: {
                // base64转blob
                base64ToBlob(base64Data) {
                    let arr = base64Data.split(','),
                        fileType = arr[0].match(/:(.*?);/)[1],
                        bstr = atob(arr[1]),
                        l = bstr.length,
                        u8Arr = new Uint8Array(l);
    
                    while (l--) {
                        u8Arr[l] = bstr.charCodeAt(l);
                    }
                    return new Blob([u8Arr], {
                        type: fileType
                    });
                }
            }
        }
    </script>
    

    三、在请求接口页面跳转到web-view页面

    // base64加密后的内容,如果放到 url中传输,就会出现空格问题,即经过加密的字符串中如果有‘+’号,就会变成空格
    // encodeURIComponent() 函数可把字符串作为 URI 组件进行编码。浏览器就可以识别了
    uni.navigateTo({
       url: './filePreview?url=' + encodeURIComponent(rest.data.PdfInfo)
    })
    

    base64 在加解密时,会用到如下64个字符

    { 'A', 'B', 'C', 'D', 'E', 'F',
      'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
      'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
      'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
      't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5',
      '6', '7', '8', '9', '+', '/' };
    

    转载自同事:https://www.yuque.com/u12033535/kg81ys/bzo0gi

    相关文章

      网友评论

          本文标题:uniapp使用pdf.js(base64)

          本文链接:https://www.haomeiwen.com/subject/zpmmvltx.html