• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
小白坤
博客园    首页    新随笔    联系   管理    订阅  订阅
vue+springboot pdf打印预览
vue+springboot pdf打印预览,文件流
pdf打印预览

1.下载pdfjs插件链接:http://mozilla.github.io/pdf.js/

2.pdfjs插件引入项目中:

①本地运行可将pdfjs放入vue项目的static文件夹下(本项目放在/static/pdf/下)

②如果在linux服务器部署建议将pdfjs单独放一个文件夹,打包可能引起访问路径的文件名发生变化,如果你有更好的方法,everything will be ok!

3.vue搞一搞

 

<el-button size="small" type="primary" @click="pdfPrint()">打印预览</el-button>

pdfPrint() {
       this.$http({
        //首先需要生成pdf文件
         url: `/project/outPdf/exportPdf`,
         method: 'post',
         data: this.dataForm
       }).then(({data}) => {
         if (data && data.code === 0) {
           let url = ''
        //根据本地和linux服务器pdf存放的位置进行配置
           if (this.$http.BASE_URL === 'http://127.0.0.1') {
             url = '/static/pdf/web/viewer.html?file='
           } else {
             url = '/pdf/web/viewer.html?file='
           }
           let pdfUrl = encodeURIComponent(this.$http.BASE_URL + `/project/outPdf/pdfFileStream?token=${this.$cookie.get('token')}&fileName=${fileName}`)
           window.open(url + pdfUrl)
         }
       })
     }        

 

 

4.后台返回文件流来一波

 

/**
   *返回文件流
 **/
@RequestMapping("/pdfFileStream")
    public void pdfStreamHandeler(String fileName,HttpServletRequest request, HttpServletResponse response) {
        try {
            String pdfPath = filePath + fileName;

            File file = new File(pdfPath);
            byte [] data = null;
            FileInputStream inputStream = null;
            inputStream = new FileInputStream(file);
            data=new byte[inputStream.available()];
            inputStream.read(data);
            response.getOutputStream().write(data);
            inputStream.close();
            response.setHeader("Access-Control-Allow-Origin", "*");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

 

 我踩过的坑希望大家都能跳过去~

posted on 2020-04-30 15:02  小白坤  阅读(3464)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3