前端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>
相关推荐
夕阳之后的黑夜10 小时前
Python脚本:为PDF批量添加水印
开发语言·python·pdf
夏沫mds11 小时前
Node.js 实现高保真 PDF 压缩:从 Canvas 方案到 Ghostscript 的踩坑实录
pdf·node.js
开开心心_Every1 天前
家长控制电脑软件:定时锁屏管理使用时长
网络协议·tcp/ip·游戏·微信·pdf·excel·语音识别
开开心心就好1 天前
免费抽奖工具支持批量导入+自定义主题
linux·运维·服务器·macos·pdf·phpstorm·1024程序员节
pass_port_csdn1 天前
zotero搬家,迁移换机/重装100% 完美克隆指南:文献PDF、插件配置、文献分类、标签、笔记等所有信息全克隆
笔记·pdf·zotero
开开心心_Every1 天前
电脑定时休息软件:久坐提醒养成活动习惯
游戏·微信·pdf·excel·语音识别·散列表·启发式算法
vlln1 天前
【调研报告】PDF解析技术现状与趋势:从人类阅读到大模型适配的需求
pdf
软件资深者2 天前
全能图片缩略图显示工具,体积较大,直接显示AI,PSD,EPS,PDF,INDD,TIFF,CR2,RAW等格式缩略图的图像解码包
windows·microsoft·pdf·windows11·系统修复
DS随心转小程序2 天前
AI公式不乱码
人工智能·pdf·deepseek·ds随心转
luyun0202022 天前
PDF神仙工具,批量处理
windows·pdf·figma