admin管理员组

文章数量:1605154

最近项目接到需求,要求下载html、word、pdf的文件,特此记录
前端:react(antd)
后端:node
包:jsdom、html-pdf、html-docx-js

<Button onClick={() => exportDownload('/后端处理api, {其他筛选逻辑}, '前端文件名');>下载</Button>
exportDownload () {
  其他筛选逻辑处理
  
  const downloadUrl = `后端文件处理api`;
  const a = document.createElement('a');
  a.href = downloadUrl;
  a.download = 前端文件名;
  a.style.display = 'none';
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
} 

后端api
我们的html直接是字符串拼接起来的,变量htmlString为我们拼接的字符串
	  // 导出html
      const html = '<html><body>' + itemThtml + '</body></html>';
      ctx.body = html;
      type = 'html';
      ctx.set('content-type', 'application/octet-stream');
      // 导出word
      const docx = HtmlDocx.asBlob(html);
      ctx.body = docx;
      type = 'docx';
      ctx.set('content-type', 'application/msword');
      // 导出pdf
      const data = await new Promise((res, rej) => {
        pdf.create(html, {format: 'A4'}).toBuffer((err, buffer) => {
          if (err) rej(err);
          res(buffer);
        });
      });
      type = 'pdf';
      ctx.body = data;
      ctx.set('content-type', 'application/pdf');

注:

  1. html中的canvas元素不能直接在word中显示,所以用JSDOM转成base64的图片,然后插入图片 const dom = new JSDOM(${HtmlString}, { runScripts: 'dangerously' });
  2. 转换之后在不同分辨率的wps中显示不同,但是在word中样式基本一致
  3. 筛选逻辑那里涉及数据库时间的:// 把客户端本地的 utc偏移量传给后端,后端才能把导出的时间变成客户端的本地时间 utcOffset: moment().utcOffset(),

本文标签: htmlnodewordPDF