VUE pdf.js 实现远程pdf文件预览

1:下载pdf

进入pdf.js官网地址:https://mozilla.github.io/pdf.js/getting_started/#download

2:将下载的pdf文件放入项目静态文件中,vue3.0的话放入到public下,如果是vue2.x版本直接放在根目录的static下

3:页面使用

4:前端api代码

export const getDownloadFile = (params) => {
    return new request({
        url: './right/right/rightLaws/getDownloadFile',
        method: 'get',
        params: params,
        responseType:'blob'
    });
}

5:前端vue对象methods中定义的方法

//预览
previewPDFFile(){
      getDownloadFile({
        lawId:this.lawIdActive
      }).then(res => {
        const content = res.data
        if(content){
          this.pathUrl  = this.getObjectURL(content);
        }else{
          this.$message.error('服务器繁忙');
        }

      }).catch(error => {
        console.log(error);
      })
},


// 将返回的流数据转换为url
getObjectURL(file) {
      var binaryData = [];
      binaryData.push(file);
      let url = null;
      if (window.createObjectURL !== undefined) { // basic
        url = window.createObjectURL(new Blob(binaryData, {type: 'application/pdf'}));
      } else if (window.webkitURL !== undefined) { // webkit or chrome
        try {
          url = window.webkitURL.createObjectURL(new Blob(binaryData, {type: 'application/pdf'}));
        } catch (error) {

        }
      } else if (window.URL !== undefined) { // mozilla(firefox)
        try {
          url = window.URL.createObjectURL(new Blob(binaryData, {type: 'application/pdf'}));
        } catch (error) {

        }
      }
      return url;
},

6:服务端文件下载接口 - 返回文件流

    /**
	 * @description 下载文件
	 */
	@ApiOperation("下载文件")
	@GetMapping("/getDownloadFile")
	public void getDownloadFile(Long lawId, HttpServletResponse response) {
		try{
			//这里仅做样例,根据个人需求,获取对应的文件全路径
            String fileName = "D:/123.pdf";
			// 读到流中
			InputStream inStream = new FileInputStream(fileName);// 文件的存放路径
			// 设置输出的格式
			response.reset();
			response.setContentType("bin");
			response.addHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode("123456.pdf", "UTF8") + "\"");
			// 循环取出流中的数据
			byte[] b = new byte[100];
			int len;
			try {
				while ((len = inStream.read(b)) > 0)
					response.getOutputStream().write(b, 0, len);
				inStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

			//}
		}catch (Exception e){
			e.printStackTrace();
		}

	}

7:最终呈现效果(谷歌浏览器,不同浏览器存在差异)

VUE pdf.js 实现远程pdf文件预览_第1张图片

 



 

你可能感兴趣的:(前端框架,前端,vue,pdf)