js 读取docx 文档 并转成html

1:使用 mammoth.js 读取 Word 文档
安装 mammoth.js 和 pica(用于前端压缩图片):

npm install mammoth pica

2: 使用 mammoth.js 读取 Word 文档

import mammoth from "mammoth";
 
methods: {
  async readWordFile(file) {
    const arrayBuffer = await file.arrayBuffer();
    const result = await mammoth.convertToHtml({ arrayBuffer: arrayBuffer });
    return result.value; // HTML string
  }
}

3: 在转换后的 HTML 中处理图片
因为mammoth 转换出来的图片是base64格式的,所以整体文档会非常大,要存db的话不太合适。
直接用来显示倒是没有问题。

import pica from "pica";
 
methods: {
  async compressImagesInHTML(html) {
    const images = html.match(/<img[^>]+src="([^">]+)"/g); // Extract image tags
    if (images) {
      images.forEach(imgTag => {
        const src = imgTag.match(/src="([^">]+)"/)[1]; // Extract src URL
        const img = new Image();
        img.src = src;
        img.onload = () => {
          const canvas = document.createElement('canvas');
          const ctx = canvas.getContext('2d');
          canvas.width = img.width;
          canvas.height = img.height;
          ctx.drawImage(img, 0, 0, img.width, img.height);
          pica().resize(img, canvas, { quality: 1 }); // Use pica for compression
          const compressedDataUrl = canvas.toDataURL('image/jpeg', 0.7); // Adjust quality as needed
          html = html.replace(src, compressedDataUrl); // Replace original src with compressed data URL
        };
      });
    }
    return html;
  }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容