基于pdf.js实现对pdf预览、批注功能、 保存下载pdf,适配H5,平板 踩坑记录

项目场景:

在APP端实现对pdf的批注,能够下载保存.能够获取批注信息同时能够重新渲染到pdf中.基于pdf.js-4.5.136版本源码实现。pc端能够正常预览下载pdf,构建打包后嵌入uniapp的webview遇到的问题记录


问题描述

将构建打包后的代码嵌入到uniapp中,运行出现Uncaught TypeError: Promise.withResolvers is not a function

bash 复制代码
10:30:27.935 同步手机端程序文件完成
10:30:29.098 正在启动HBuilder调试基座...
10:30:30.103 应用【移动端测试】已启动
10:30:30.294 [Object] {"errMsg":"reLaunch:fail page `/` is not found"}  at permission.js:37
10:30:30.807 Uncaught TypeError: Promise.withResolvers is not a function at hybrid/html/web/viewer.mjs:24062
复制代码

解决方案:

源码构建打包用的gulp generic出现上述问题,采用gulp generic-legacy(兼容低版本浏览器)构建方式即可

问题描述

app.js:1173加载 PDF 时发生错误。 PDF.js v? (build: ?) Message: file origin does not match viewer's

bash 复制代码
app.js:1173 加载 PDF 时发生错误。

PDF.js v? (build: ?)
Message: file origin does not match viewer's

复制代码

解决方案:

将pdf.js中app.js的跨域拦截去掉重新构建, 或者直接修改构建后的viewer.js的validateFileURL方法

javascript 复制代码
var validateFileURL = function (file) {
    if (!file) {
      return;
    }
    try {
      const viewerOrigin = new URL(window.location.href).origin || "null";
      if (HOSTED_VIEWER_ORIGINS.includes(viewerOrigin)) {
        // Hosted or local viewer, allow for any file locations
        return;
      }
      const fileOrigin = new URL(file, window.location.href).origin;
      // Removing of the following line will not guarantee that the viewer will
      // start accepting URLs from foreign origin -- CORS headers on the remote
      // server must be properly configured.
      
       //去掉下面这段==========================
    /*if (fileOrigin !== viewerOrigin) {
        throw new Error("file origin does not match viewer's");
      }*/

    } catch (ex) {
      PDFViewerApplication._documentError("pdfjs-loading-error", {
        message: ex.message,
      });
      throw ex;
    }
  };

APP端下载pdf,需要更改下载方法,将pc端的下载方式改为移动端下载。通过uniapp的webview之间的通信,将文件流转成base64传到uniapp端处理下载保存到本地,更改viewer.j的下载方法

javascript 复制代码
function download(blobUrl, filename) {
  //通过bloburl获取到blob对象再转成base64,传输到父页面uniapp端
  fetch(blobUrl)
  	 .then(response => response.blob())
  	 .then(blob => {
  		
  		const reader = new FileReader();
  			reader.readAsDataURL(blob);
  			reader.onload = () => {
  			  const base64 = reader.result;
  			  uni.postMessage({
  					  data: {
  						blob: base64
  					  },
  					});
  			} 
  	})

  //下面是pc端的下载方式,注释掉
  //const a = document.createElement("a");
  //if (!a.click) {
  //  throw new Error('DownloadManager: "a.click()" is not supported.');
  //}
  //a.href = blobUrl;
  //a.target = "_parent";
  //if ("download" in a) {
  //  a.download = filename;
  //}
  //(document.body || document.documentElement).append(a);
  //a.click();
  //a.remove();
}

问题描述

在APP端下载,下载后的文件不含批注,只是源文件下载

复制代码

解决方案:

通过跟踪源码,发现app端下载和pc端不同,

显然再APP保存文档的时候,出现异常,通过跟踪发现,批注存储序列化的时候出现分歧

javascript 复制代码
get serializable() {
    if (this.#storage.size === 0) {
      return SerializableEmpty;
    }
    const map = new Map(),
      hash = new MurmurHash3_64(),
      transfer = [];
    const context = Object.create(null);
    let hasBitmap = false;
    for (const [key, val] of this.#storage) {
      
      //const serialized = val instanceof AnnotationEditor ? val.serialize(false, context) : val;
	  //此处针对批注的value,强制序列化即可
      const serialized = val.serialize(false, context);


      if (serialized) {
        map.set(key, serialized);
        hash.update(`${key}:${JSON.stringify(serialized)}`);
        hasBitmap ||= !!serialized.bitmap;
      }
    }
    if (hasBitmap) {
      for (const value of map.values()) {
        if (value.bitmap) {
          transfer.push(value.bitmap);
        }
      }
    }
    return map.size > 0 ? {
      map,
      hash: hash.hexdigest(),
      transfer
    } : SerializableEmpty;
  }
相关推荐
李少兄8 小时前
CSS clip-path:前端开发中的裁剪技术
前端·css
zhengxianyi5158 小时前
使用码云gitee登录ruoyi-vue-pro——坑比较多
前端·vue.js·gitee·ruoyi-vue-pro优化·三方登陆
光影少年8 小时前
React vs Next.js
前端·javascript·react.js
谢尔登8 小时前
Vue3 响应式系统——ref 和 reactive
前端·javascript·vue.js
OEC小胖胖8 小时前
16|总复习:把前 15 章串成一张 React 源码主线地图
前端·react.js·前端框架·react·开源库
董世昌418 小时前
HTTP协议中,GET和POST有什么区别?分别适用什么场景?
java·开发语言·前端
_OP_CHEN8 小时前
【前端开发之HTML】(二)HTML 常见标签(上):从入门到实战,搞定网页基础排版!
前端·css·html·前端开发·网页开发·html标签
满栀5858 小时前
插件轮播图制作
开发语言·前端·javascript·jquery
切糕师学AI8 小时前
Vue 中的计算属性(computed)
前端·javascript·vue.js
程琬清君9 小时前
Vue3DraggableResizable可移动范围有问题
前端·javascript·vue.js