VUE + pdfh5 实现pdf 预览

1. 安装依赖

npm install pdfh5

2.vue2 实例

  • vue 文件中 创建div 节点
<template>
  <div class="wrap">
    <div id="demo"></div>
  </div>
</template>
  • js 中配置
<script>
import Pdfh5 from "pdfh5";  // 这两个一定要引入
import "pdfh5/css/pdfh5.css"; // 这两个一定要引入, 这个是在加载时,顶部会出来一个加载进度条和一些其他的样式
export default {
  name: "openPdf",
  data() {
    return {
      pdfh5: null,
    };
  },
  mounted() {
    // ---------------------------- 方法一 -----------------------------
    this.pdfh5 = new Pdfh5("#demo", {
      pdfurl: "https://www.*********uanfu.pdf", // pdf 地址,请求的地址需要为线上的地址,测试的本地的地址是不可以的
      lazy: true, // 是否懒加载
      withCredentials: true,
      renderType: "svg",
      maxZoom: 3, //手势缩放最大倍数 默认3
      scrollEnable: true, //是否允许pdf滚动
      zoomEnable: true, //是否允许pdf手势缩放
    });
    // --------------------------- 方法二 ---------------------------
    //实例化
    this.pdfh5 = new Pdfh5("#demo", {
        pdfurl: "https://www**********anfu.pdf",
    });
    //监听完成事件
    this.pdfh5.on("complete", function (status, msg, time) {
        console.log("状态:" + status +",信息:" +msg +",耗时:" + time + "毫秒,总页数:" + this.totalNum);
    });
  },
};
</script>
 
  • CSS 样式配置
<style>
.wrap {
  width: 100%;
  height: 100%;
  background-color: #fff;
}
/* html,
body, */
#demo {
  width: 100%;
  height: 100%;
}
// 这里高度没有撑满
.viewerContainer {
  height: 100%;
}
</style>

3. Vue3 实例

import Pdfh5 from "pdfh5";
import "pdfh5/css/pdfh5.css";

const refPdf = ref(null);
const LoadPdf = (url) => {
  const pdfh5 = new Pdfh5(refPdf.value, {
    pdfurl: url,
  });
  pdfh5.on("complete", (status, msg, time) => { });
};

const getDocById = (id) => {
  readPDF(id).then((res) => {
    if (res) {
      LoadPdf(window.URL.createObjectURL(new Blob([res])));
    }
  });
}

api

export function readPDF(id) {
  return request({
      url: 'business/document/readPDF/'+ id,
      method: 'get',
      responseType: 'blob'
  })
}

SpringBoot 后台代码

Controller

 @ApiOperation("查看PDF资料")
    @ApiOperationSupport(order = 5)
    @ApiImplicitParam(name = "dataId", value = "资料Id", required = true)
    @GetMapping("/readPDF/{dataId}")
    @RepeatSubmit
    public void readPDF(@PathVariable Long dataId, HttpServletResponse response) {
        documentInfoService.readPDF(dataId, response);
    }

Service

 public void readPDF(Long dataId, HttpServletResponse response) {
        BiDocumentInfo documentInfo = documentInfoMapper.selectById(dataId);
        response.reset();
        response.setContentType("application/pdf");
        InputStream inputStream = null;
        OutputStream outputStream = null;
        if (!StringUtils.isEmpty(documentInfo.getDocAttachment())) {
            String[] pathAndName = documentInfo.getDocAttachment().split("\\|");
            File file = new File(localPath + pathAndName[0]);

            //读取生成的PDF文件
            try {
                if (file.exists()) {
                    String filename = URLEncoder.encode(pathAndName[1], "UTF-8");
                    response.setHeader("Content-Disposition", "inline; filename=" + filename);
                    response.addHeader("Access-Control-Allow-Origin", "*");
                    inputStream = new FileInputStream(file);
                    outputStream = new BufferedOutputStream(response.getOutputStream());
                    byte[] bytes = new byte[1024];
                    int len;
                    while ((len = inputStream.read(bytes)) != -1) {
                        outputStream.write(bytes, 0, len);
                    }
                    outputStream.flush();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if (outputStream !=null){
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (inputStream !=null){
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }
        }

    }
  • 0
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
在Spring Boot和Vue项目中实现PDF在线预览可以通过集成pdf.js库来实现。首先,您需要从官网下载pdf.js源码,并将其放入您的项目中。具体步骤如下: 1. 在官方网站下载pdf.js源码。 2. 将下载的源码放入您的Spring Boot项目中的某个目录中。 3. 打开viewer.html文件,您会注意到它会自动跳转到一个pdf文件。这个pdf文件是官方的示例文件。 4. 如果您只想打开一个特定的pdf文件,只需将官方示例文件替换为您自己的pdf文件。 5. 在viewer.js文件中搜索"defaultUrl",大约在第3500行左右。您可以找到类似上述代码的部分(注意:不同版本的pdf.js可能会略有差异)。 6. 只需更改"value"的值,即可实现预览您指定的pdf文件。 7. 如果您需要根据前端传递的不同值来响应不同的pdf文件,可以使用动态获取的方式来实现。 另外,如果希望使用浏览器自带的预览pdf功能,可以参考使用pdf.js的实现方式。但需要注意的是,某些浏览器可能不支持此功能,如360浏览器。您可以在我的博客中找到有关使用浏览器预览pdf的更多信息。 综上所述,您可以根据以上步骤在Spring Boot和Vue项目中实现PDF在线预览。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [springboot+vue整合pdf.js实现预览pdf](https://blog.csdn.net/qq_14853853/article/details/111176085)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值