实现思路
1.将Word文档转换为HTML:mammoth.js,它可以将.docx文件转换为HTML
2.将HTML转换为PDF:使用html2html" title=pdf>pdf.js将HTML转换为PDF
如果想要相同的效果,也可以把前端页面直接导出转换为html" title=pdf>pdf: 运用的插件:html2html" title=pdf>pdf.js
后端文件流导出接口返回:
首先我们要安装mammoth.js和html2html" title=pdf>pdf.js
npm install mammoth jshtml" title=pdf>pdf
代码:
// 引入
import mammoth from "mammoth";
import html2html" title=pdf>pdf from "html2html" title=pdf>pdf.js";
<el-button type="primary" :loading="isLoading" @click="healthExport">
导出
</el-button>
async function healthExport() {
try {
await signatureApi
.onReportWord({
id: selectedData.value[0].id,
signId: selectedData.value[0].healthyId,
})
.then((res) => {
if (res) {
const reader = new FileReader();
reader.onload = (e) => {
const arrayBuffer = res;
mammoth
.convertToHtml({ arrayBuffer: arrayBuffer })
.then((result) => {
const htmlContent = result.value; // 这是转换后的HTML内容
// 将HTML添加到页面的一个隐藏div中
var div = document.createElement("div");
// 可以给html" title=pdf>pdf自定义添加样式(将html" title=word>word提取html再转换成html" title=pdf>pdf导出这时候html" title=pdf>pdf是没有样式的)
const css = `<style>body { p { text-align:center;font-size:20px;soild }</style>`;
div.innerHTML = `<html>${css}${htmlContent}</html>`;
document.body.appendChild(div);
// 使用html2html" title=pdf>pdf.js将HTML转换为PDF
html2html" title=pdf>pdf()
.from(div)
.set({
html2canvas: { scale: 2 },
jsPDF: { format: "a4", orientation: "portrait" },
css: css,
})
.save("document.html" title=pdf>pdf");
// 清理 - 移除添加的div
document.body.removeChild(div);
})
.catch((err) => {
console.error(err);
});
};
reader.readAsArrayBuffer(res);
}
});
} catch (error) {
console.error("err", error);
}
}
第二种前端思路:把前端页面直接导出转换为html" title=pdf>pdf
页面:点击导出直接导出为html" title=pdf>pdf
<el-button type="primary" :loading="isLoading" @click="handleExport">
导 出
</el-button>
function handleExport() {
html2html" title=pdf>pdf().set({
html2canvas: { scale: 3 }, // 增加缩放比例以提高清晰度
jsPDF: { unit: 'in', format: 'a4', orientation: 'portrait' } // 设置单位和纸张大小
}).from(document.getElementById('html" title=pdf>pdfRef')).save('健康体检通知书.html" title=pdf>pdf');
}