前端实现预览pdf,后端返回文件流或者base64

预览pdf

返回文件流
首先接口一定要设置响应类型
responseType: ‘blob’,
或者
responseType: ‘arraybuffer’, //一定要设置响应类型,否则页面会是空白pdf

API(data)
        .then((res) => {
          let _this = this;
          try {
	//抛出错误信息
            if (res.type.indexOf("application/json") > -1) {
              const reader = new FileReader();
              reader.readAsText(res, "utf-8");
              reader.onload = function () {
                const { msg } = JSON.parse(reader.result);
                _this.$message({
                  message: msg,
                  type: "error",
                });
                //reader.result里面含报错信息
              };
              return;
            }
            const binaryData = [];
            binaryData.push(res);
            const url = window.URL.createObjectURL(
              new Blob(binaryData, { type: "application/pdf" })
            );
            this.pdfUrl = url;//直接用iframe标签
            // this.linkUrl = url;
            // window.open(url)//新窗口打开
          } catch (err) {}
        })
        .finally(() => {
        });

加了#toolbar=0,少了显示操作栏

  <iframe
    :src="pdfUrl + '#toolbar=0'"
    style="border: none"
    frameborder="0"
    height="600px"
    width="100%"
    scrolling="no"
    marginheight="0px"
    marginwidth="0px"
    v-if="pdfUrl"
  ></iframe>```



如果返回的是base64

```javascript
   //     // parmsFiles 就是后台给你返回的一串流
        //     const pdf = "data:application/pdf;base64," +parmsFiles ;
        //     // this.pdfUrl = pdf;
        //     window.document.write(
        //       '<iframe src="' +
        //         pdf +
        //         '" frameborder="0" style="border:0; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%;"></iframe>'
        //     );
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值