vue3&vite4使用pdfH5遇到的坑记录

283 阅读1分钟

一、不能仅安装pdfH5,还要相关依赖包,否则会报错

npm i pdfh5
npm i canvas dommatrix web-streams-polyfill

[ERROR] Could not resolve "canvas"

node_modules/pdfh5/js/pdf.js:22:244110:
  22 │ ...lue:function _createCanvas(t,r){return require("canvas").createCanvas(t,r)}}]);return NodeCanvasFactor...
     ╵                                                   ~~~~~~~~

You can mark the path "canvas" as external to exclude it from the bundle, which will remove this error and leave the unresolved path in the bundle. You can also surround this "require" call with a try/catch block to handle this failure at run-time instead of bundle-time.

二、package.json增加以下配置, 否则也会报错

 "browser": {
    "canvas": false,
    "fs": false,
    "http": false,
    "https": false,
    "url": false,
    "zlib": false
  },

三、预览本地pdf时的地址问题


  import Pdfh5 from "pdfh5";
  import "pdfh5/css/pdfh5.css";
  import { useRoute } from 'vue-router';
  const route = useRoute();
 const mypdf = ref()
  const title = ref('');
  onMounted(()=>{
  //注意guide.pdf放到public文件夹下,以下这种方式写着保险,不用直接用‘/guide.pdf’会导致有路由前缀时访问不到,也可以这样写`${import.meta.env.BASE_URL}/agreement.pdf`
     new Pdfh5(mypdf.value, {
      pdfurl: './guide.pdf'
    });


  })