1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| const mammoth = require('mammoth') const fs = require('fs') const path = require('path')
function getFileConfig() { const inputDir = path.resolve(__dirname, 'input'); const files = fs.readdirSync(inputDir).filter(f => f.endsWith('.docx')); return files.map(f => { return { inputPath: path.join(__dirname, 'input',f), outputPath: path.join(__dirname, 'output', f.replace('.docx', '.html')) } }); }
function transformParagraph(element) { let styleName = ""; if (element.alignment === "center") { styleName = "text-center"; } else if (element.alignment === "right") { styleName = "text-right"; } return { ...element, styleName }; }
const options = { styleMap: [ "p[style-name='text-center'] => p.text-center:fresh", "p[style-name='text-right'] => p.text-right:fresh", "u => span.text-underline:fresh" ], transformDocument: mammoth.transforms.paragraph(transformParagraph) }
const convertToHtml = (config) => { const { inputPath, outputPath } = config; return mammoth.convertToHtml({ path: inputPath }, options).then(function(result){ const html = result.value const templatePath = path.join(__dirname, 'template.html') const tempHtml = fs.readFileSync(templatePath, 'utf8') const insertTag = '<div id="app">' const insertIndex = tempHtml.lastIndexOf(insertTag) + insertTag.length const resHtml = tempHtml.slice(0, insertIndex) + html + tempHtml.slice(insertIndex) fs.writeFileSync(outputPath, resHtml, 'utf8') }).catch(function(err){ console.log(err); }); }
const allFileConfig = getFileConfig(); const allFileConfigLength = allFileConfig.length; // 清空 output 目录 if (fs.existsSync(path.join(__dirname, 'output'))) { fs.rmdirSync(path.join(__dirname, 'output'), { recursive: true, force: true }); } fs.mkdirSync(path.join(__dirname, 'output'));
let index = 0; console.log(`开始转换,共 ${allFileConfigLength} 个文件`); function runNext() { if (index >= allFileConfigLength) { console.log('文件转换完成,请查看 output 目录'); return; } const config = allFileConfig[index]; console.log(`${index + 1}: ${path.basename(config.inputPath)}`); convertToHtml(config).then(() => { index++; runNext(); }).catch(err => { console.error(`Error processing file ${path.basename(config.inputPath)}:`, err); index++; runNext(); }); }
runNext();
|