前端web端解析 Word、Pdf 文档文本内容

一、使用 mammoth.js 解析 word 文档

需要注意的是在 web 端使用mammoth.js 解析 word 文档时需要引入mammoth.js 的浏览器版本,否则虽然本地能够正常运行,但是打包到线上就会报错。

javascript 复制代码
import * as mammoth from "mammoth/mammoth.browser.min.js";


  /**
   * 解析 Word 文档
   */
  private async parseWordDocument(file: File): Promise<string> {
    const arrayBuffer = await file.arrayBuffer();
    const result = await mammoth.extractRawText({ arrayBuffer });
    return result.value;
  }

二、使用 pdfjs-dist 解析 pdf 文档

1,安装依赖. "pdfjs-dist": "^5.4.530",

npm i pdfjs-dist -D

2,添加 webworker 文件

在项目中的public 目录中创建 pdf-workers 目录,并把node_modules 中的pdfjs-dist 下面的build 目录下的pdf.worker.min.mjs 复制粘贴进 pdf-workers 目录中

3,解析 pdf 文档中的文本内容

javascript 复制代码
import * as pdfjsLib from "pdfjs-dist";


// 设置 PDF.js worker
if (typeof window !== "undefined") {
  // 从 public/pdf-workers 文件夹加载 worker
  pdfjsLib.GlobalWorkerOptions.workerSrc = "/pdf-workers/pdf.worker.min.mjs";
}


  /**
   * 解析 PDF 文档
   */
  private async parsePdfDocument(file: File): Promise<string> {
    const arrayBuffer = await file.arrayBuffer();
    const pdf = await pdfjsLib.getDocument({ data: arrayBuffer }).promise;

    let text = "";
    for (let i = 1; i <= pdf.numPages; i++) {
      const page = await pdf.getPage(i);
      const textContent = await page.getTextContent();
      const pageText = textContent.items.map((item: any) => item.str).join(" ");
      text += pageText + "\n";
    }
    text = text.replace(/\u0001/g, " ");
    return text;
  }

三、解析 pdf 文档添加 polyfill 兼容低版本浏览器

在某些低版本浏览器中可能会提示 not fond promiseWidthResolvers , 需要增加一个polyfill

1, 在 pdf-workers 中创建一个 pdf-polyfill.js 文件

javascript 复制代码
if (typeof Promise.withResolvers === 'undefined') {
  Promise.withResolvers = function () {
    let resolve, reject
    const promise = new Promise((res, rej) => {
      resolve = res
      reject = rej
    })
    return { promise, resolve, reject }
  }
}

2,在 index.html 文件中进入 pdf-polyfill.js 文件

javascript 复制代码
    <script type="module" src="/pdf-workers/pdf-profill.js"></script>
相关推荐
小贺儿开发12 小时前
Unity3D 心理沙盘互动演示
unity·ai·pdf·人机交互·工具·互动·心理沙盘
私人珍藏库14 小时前
[Windows] PDF工具箱 PDF24 Creator 11.30.0
windows·pdf·工具·软件·多功能
zhensherlock14 小时前
Protocol Launcher 系列:Mail Assistant 轻松发送 HTML 邮件
前端·javascript·typescript·node.js·html·github·js
彭于晏Yan15 小时前
基于iText7的动态PDF生成技术方案
spring boot·pdf
悟乙己15 小时前
Advanced RAG 02:揭秘 PDF 解析
ai·pdf·llm·文档解析
lq123321016 小时前
PDF工具箱 PDF24 Creator 11.30.0
pdf
cuoluoche16 小时前
postman接口请求response是base64-图片这类的可视化。
js
Huanzhi_Lin1 天前
关于V8/MajorGC/MinorGC——性能优化
javascript·性能优化·ts·js·v8·新生代·老生代
忧郁的Mr.Li1 天前
JAVA工具类---PDF电子签章工具类
java·pdf
AscendKing1 天前
免费、易用、覆盖全平台的网页转 PDF 工具
pdf·html·网页保存·网页保存为pdf·保存网页位pdf