自学内容网 自学内容网

基于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

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

app.js:1173 加载 PDF 时发生错误。

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

 

解决方案:

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

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的下载方法

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保存文档的时候,出现异常,通过跟踪发现,批注存储序列化的时候出现分歧

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


原文地址:https://blog.csdn.net/zhangyongbink/article/details/142517191

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!