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');
注:
- html中的canvas元素不能直接在word中显示,所以用JSDOM转成base64的图片,然后插入图片
const dom = new JSDOM(
${HtmlString}, { runScripts: 'dangerously' });
- 转换之后在不同分辨率的wps中显示不同,但是在word中样式基本一致
- 筛选逻辑那里涉及数据库时间的:
// 把客户端本地的 utc偏移量传给后端,后端才能把导出的时间变成客户端的本地时间 utcOffset: moment().utcOffset(),
版权声明:本文标题:node实现,下载html、pdf、html(html转word、pdf) 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dongtai/1728480307a1160034.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论