您当前的位置:首页 > 计算机 > 编程开发 > Html+Div+Css(前端)

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

时间:01-19来源:作者:点击数:
城东书院 www.cdsy.xyz

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

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

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 文档中的文本内容

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 文件

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 文件

    <script type="module" src="/pdf-workers/pdf-profill.js"></script>
城东书院 www.cdsy.xyz
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐