在开发时经常会遇到文件导出为另外一个格式的需求,如将 HTML 导出为 WORD。 pandoc 是一个通用的用于转换文件格式的命令行工具,很好用。


typescript
app.get('/export/word/:id', async (req, res) => {
  try {
    const html = await getHTML(req.params.id as string);

    const tmpFileName = `file_${new Date().getTime()}.docx`;
    execSync(`rm -rf /tmp/${tmpFileName} || true`);
    execSync(`pandoc -f html -t docx -o /tmp/${tmpFileName}`, {
      input: html
    });

    res.on('finish', () => {
      execSync(`rm -rf /tmp/${tmpFileName}`);
    });

    res.setHeader('Content-Type', 'application/msword');
    res.setHeader(
      'Content-Disposition',
      `attachment; filename="${tmpFileName}"`
    );
    res.sendFile(`/tmp/${tmpFileName}`);
  } catch (error) {
    console.error('导出 Word 失败:', error);
    res.status(500).json({ error });
  }
});
Author's avatar

专注计算机科学与技术

鼓励作者

感谢你赐予我前进的动力!

微信
支付宝
© 版权声明: 此文章为作者原创文章,采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源!

基于 MIT 许可发布

版权所有 © 2024-2025 向成渝