前言:在项目开发过程中,可能会遇到在线预览pdf的功能,我就遇到了,期间真是一把心酸一把泪啊,最终把可以使用的结果记录下来,以便后面少采坑。

一、vue使用pdfjs

1、下载pdfjs

我把插件文件上传到csdn上了,下载地址

2、把下载的文件放到static下

我把文件放到了static/plugins/pdf下了,具体的位置可以自行调整
在这里插入图片描述

3、新建一个templete模板

模板中加入以下内容,获取到的pdf文件是以流的形式返回给插件的
html内容如下

<template>
  <div class="mod-config" v-loading="loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)" style="height:100%">
    <iframe width="100%" height="100%" scrolling="no" :src="`/static/plugins/pdf/web/viewer.html?file=${src}`"></iframe>
  </div>
</template>
<script>
  export default {
    data () {
      return {
        src: null,
        loading: false
      }
    },
    activated () {
      this.getPdfCode();
    },
    methods: {
      getPdfCode: function() {
      	this.loading=true;
        this.prohibit();
        let pdfId=this.$route.query.id;
        let pdfUrl=encodeURIComponent(this.$http.adornUrl(`/file/pdfView/`+pdfId));
        if(pdfId){
          this.src = pdfUrl;
          this.loading=false;
        }
      },
       // 禁用鼠标右击、F12 来禁止打印和打开调试工具
      prohibit () {
        document.oncontextmenu=function(ev){
          return false;    //屏蔽右键菜单
        }
        document.onkeydown = function (e) {
          if (e.ctrlKey && (e.keyCode === 65 || e.keyCode === 67 || e.keyCode === 73 || e.keyCode === 74 || e.keyCode === 80 || e.keyCode === 83 || e.keyCode === 85 || e.keyCode === 86 || e.keyCode === 117)) {
            return false
          }
          if (e.keyCode === 18 || e.keyCode === 123) {
            return false
          }
        }
      }
    },
    mounted(){
      this.$nextTick(()=>{
        this.getPdfCode();
      });
    }
  }
</script>
<style>
  *{
	padding: 0;
	margin: 0;
	}
	html,body,#app {
	width: 100%;
	height: 100%;
	}
  @media print{
  * {display:none}
  }
</style>

java内容如下

@Controller
@RequestMapping("/file")
public class FileController {

    @Autowired
    private ViewService viewService;
    /**
     * pdf服务器保存路径
     */
    @Value("${pdf.path}")
    private String pdfPath;

    @RequestMapping("/pdfView/{id}")
    public void pdfView(HttpServletResponse response, @PathVariable("id") Long id) {
        if(id!=null){
            try {
                try {
                    ViewEntity view = viewService.getById(id);
                    if(view!=null){
                        if(StringUtils.isNotBlank(view.getUrl())){
//                            File filePic = new File(view.getUrl());
                            File filePic = new File(pdfPath+File.separator+view.getUrl());
                            if(filePic.exists()){
                                FileInputStream fis = new FileInputStream(filePic);
                                response.reset();
                                // 解决跨域问题,这句话是关键,对任意的域都可以,如果需要安全,可以设置成安前的域名
                                response.addHeader("Access-Control-Allow-Origin", "*");
                                response.setContentType("application/octet-stream");
                                response.setCharacterEncoding("utf-8");
                                byte[] buff = new byte[1024];
                                BufferedInputStream bis = null;
                                OutputStream os = null;
                                try {
                                    os = response.getOutputStream();
                                    bis = new BufferedInputStream(fis);
                                    int i = 0;
                                    while ((i = bis.read(buff)) != -1) {
                                        os.write(buff, 0, i);
                                        os.flush();
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                } finally {
                                    try {
                                        bis.close();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    }
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }
}

以上设置完毕后就可以使用pdfjs进行预览了,但是在使用的过程中也遇到了一些问题,下面进行一下总结。

二、遇到的问题

1、IE浏览器兼容问题

在使用npm安装了pdfjs-dist后,按照上面的操作,报ES6语法错误,IE浏览器不支持ES6的语法,在网上查看了各种IE浏览器兼容ES6的配置,最后放弃了。
不过也总结了一些经验

1、安装babel-polyfill

npm install pdfjs-dist --save

2、在main.js文件中引入

注意:要放在文件最上方


import "babel-polyfill"
import Vue from 'vue'

3、在webpack.base.conf.js文件中修改代码如下

entry: {
	// pp: './src/main.js'
    app: ['babel-polyfill', './src/main.js']
  },

最后加上这些设置也还是说语法有问题

2、跨域问题

1、注释viewer.js的代码

//    if (fileOrigin !== viewerOrigin) {
//      throw new Error('file origin does not match viewer\'s');
//    }

最后经过修改源码,把不支持的语法都修改了一遍后,可以使用了,希望后面遇到相同的问题,可以立马得到解决。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐