查看、预览pdf的需求,h5,移动端 该如何使用pdfjs?

940 阅读1分钟

首先,移动端查看pdf,由于不同的系统,需要多种适配。这里选取pdf.js 和iframe 1.下载:选择旧版本的(第二个),下载获取压缩包,解压后放入项目。官网地址下载: mozilla.github.io/pdf.js/,

2.注意:把解压后文件放在一个文件夹里,文件夹取名:pdfjs,放到项目根目录文件夹下。放在不会被打包压缩的地方,比如 如果项目有 public,就放在public文件夹下,如果是h5之类没有public文件夹,放在src同级的位置就可以

3.实际使用:(vue3+h5)

  <template>
    <div>
      <iframe
        width="100%"
        style="height: 100vh; border: none"
        :src="pdfSrc"
      ></iframe>
    </div>
 </template>
 <script lang="ts" setup>
    const pdfSrc = ref(null);
    onMounted(() => {
      //获取pdf文件的 url.这里返回的是http形式的url,不是流。
      const pdfurl = route.query.fileUrl as string;
      //我是放在src同级的位置,文件路径是:/pdfjs/web/viewer.html?file=
      //如果放在public下文件路径是:pdfjs/web/viewer.html?file=
      
      pdfSrc.value = `${
        window.location.origin + window.location.pathname
      }/pdfjs/web/viewer.html?file=${encodeURI(pdfurl)}`;
      
      console.log("pdfSrc", pdfSrc.value);
      //如果获取到的pdf文件的是 流 的形式,需要用encodeURIComponent()
      //  pdfSrc.value = `${
      //   window.location.origin + window.location.pathname
      // }/pdfjs/web/viewer.html?file=${encodeURIComponent(pdfurl)}`;
     
    });
 </script>

4.另外,在使用中可能会遇到跨域的问题,出现报错:# file origin does not match viewer's 从下载解压的文件夹中找到web/viewer.js 或者web/viewer.mjs(不同版本文件稍有区别),找到其中写着:new Error('file origin does not match viewer's'); 的部分,注释掉对应的判断部分代码 例如: if (origin !== viewerOrigin && protocol !== 'blob:') {
throw new Error('file origin does not match viewer's');
} 或者 if (fileOrigin !== viewerOrigin) { throw new Error("file origin does not match viewer's"); }