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: 在轉(zhuǎn)換后的 HTML 中處理圖片
因?yàn)閙ammoth 轉(zhuǎn)換出來的圖片是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;
}
}