前端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>
相关推荐
weixin_469273814 小时前
如何在线把文字转为 pdf 文档
pdf
2601_963906785 小时前
离线截图 OCR 识别:支持表格与 PDF 解析
pdf·ocr·软件需求
asdzx6713 小时前
Python 实现 PDF 文本查找与高亮标注
开发语言·python·pdf
laoban-yu13 小时前
Word与PDF文档互转
pdf·word·文档转换
鲲穹AI种草2 天前
PDF 文档多格式转换处理,多款 PDF 处理工具能力客观记录
pdf·文档格式转换
Felicia-侧听2 天前
PDF怎么转换成OFD?在线PDF转OFD方法
pdf·pdf转换·ofd·电子发票·文件格式转换·pdf转ofd·ofd格式
开开心心_Every3 天前
实现鼠标键盘动作录制与重复播放的工具
微信·jupyter·pycharm·pdf·计算机外设·word·excel
2601_962299493 天前
使用 Python 将 CSV 转为 PDF(含表格样式美化)
python·pdf·csv·spire.xls·表格样式
tianyue1004 天前
PDFsam Basic PDF 分割、合并
pdf
SunnyDays10114 天前
如何使用 Python 给 PDF 添加附件:文档附件与附件注释
开发语言·python·pdf