基于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;
  }
相关推荐
汪子熙42 分钟前
CSS Style position: absolute 的含义
前端·css
晴天蜗牛不一般1 小时前
隆重的给大家介绍一下 <BaseEcharts/>
前端·npm·echarts
ceek@1 小时前
HTML增加复制模块(使用户快速复制内容到剪贴板)
前端·javascript·html
小于负无穷1 小时前
前端面试题(十)
前端
Tim20231 小时前
202409使用eslint与prettier的实战
前端
黄毛火烧雪下1 小时前
前端注释规范
前端
声声codeGrandMaster2 小时前
Vue入门2
前端·vue.js·vue
爱吃水果和蔬菜丫2 小时前
解决sortablejs+el-table表格内限制回撤和拖拽回撤失败问题
前端
NiNg_1_2342 小时前
Axios 和 Ajax的区别和联系
前端·javascript·ajax