VUE + pdfh5 realizes pdf preview

1. Install dependencies

npm install pdfh5

2. vue2 instance

  • Create a div node in the vue file
<template>
  <div class="wrap">
    <div id="demo"></div>
  </div>
</template>
  • js configuration
<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 configuration
<style>
.wrap {
    
    
  width: 100%;
  height: 100%;
  background-color: #fff;
}
/* html,
body, */
#demo {
    
    
  width: 100%;
  height: 100%;
}
// 这里高度没有撑满
.viewerContainer {
    
    
  height: 100%;
}
</style>

3. Vue3 instance

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 background code

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();
                    }
                }

            }
        }

    }

Guess you like

Origin blog.csdn.net/u014212540/article/details/129408653