pdfJS在实际项目中的实践(Vue版本,React只需要部分修改即可)

332 阅读1分钟

1、JS文件地址 链接: pan.baidu.com/s/1EuQsztXm… 提取码: r1q5

2、将build、web文件夹放在public中的static文件夹下

3、封装组件:

    注意要引入axios包
    函数1获取PDF文件,alarmID是我需要的接口ID(这个要根据你的接口要求就写),urlBase是拿到服务器的请求地址(根据实际情况进行修改),token服务器效验密令。
    //以下是Vue版本,封装的组件
    ```
<template>
    <iframe  :src="pdfUrl" width="100%" :height="clHeight"></iframe>
</template>

<script>
import axios from 'axios'
import store from '@/store/'
export default {
  name: 'PDFDetail',
  data() {
    return {
      data: [],
      pdfUrl: '',
      clHeight:'980px'
    }
  },
  mounted() {
    let alarmId = localStorage.getItem("alarmId")
    this.getPdfCode(alarmId)
    this.clHeight = document.body.clientHeight + 'px'
  },
  methods: {
    // 初始化获取pdf文件
    getPdfCode(alarmId) {
      let that = this;
      let urlBase = process.env.VUE_APP_API_BASE_URL
      let token = store.getters.token
      axios({
        method: 'get',
        url: urlBase + '/alarm/handle/export' + "?id=" + alarmId,
        headers: {
          'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          'X-Access-Token': token
        },
        responseType: 'blob'  //设置响应的数据类型为一个包含二进制数据的 Blob 对象,必须设置!!!
      }).then(response => {
        that.pdfUrl = that.getObjectURL(response.data);
      }).catch(function (error) {
        console.log(error);
      });
    },
    // 将返回的流数据转换为url
    getObjectURL(file) {
      let url = null;
      if (window.createObjectURL != undefined) { // basic
        url = window.createObjectURL(file);
      } else if (window.webkitURL != undefined) { // webkit or chrome
        try {
          url = window.webkitURL.createObjectURL(file);
        } catch (error) {

        }
      } else if (window.URL != undefined) { // mozilla(firefox)
        try {
          url = window.URL.createObjectURL(file);
        } catch (error) {
        }
      }
      return url;
    },
  },
}
</script>

<style lang='less' scoped>
</style>

4、使用

      //'/pdfDetail'为路由地址,这个要根据组件渲染地址去进行修改,这是在新窗口打开页面
      var iWidth = 800; //弹出窗口的宽度;
      var iHeight = 400; //弹出窗口的高度;
      var iTop = (window.screen.height - 30 - iHeight) / 2; //获得窗口的垂直位置;
      var iLeft = (window.screen.width - 10 - iWidth) / 2; //获得窗口的水平位置;
      window.open('/pdfDetail', '_blank', 'height=' + iHeight + ',innerHeight=' + iHeight + ',width=' + iWidth + ',innerWidth=' + iWidth + ',top=' + iTop + ',left=' +iLeft + ',toolbar=no,menubar=no,scrollbars=auto,resizeable=no,location=no,status=no')

5、使用时有技术问题可以随时留言,在各种框架中大家都可能遇到写PDF文件,根据不同框架进行书写格式部分修改即可,谢谢大家。