vue3.0将后端返回的word文件流转换为pdf并导出+html2pdf.js将页面导出为pdf
实现思路
1.将Word文档转换为HTML:mammoth.js,它可以将.docx文件转换为HTML
2.将HTML转换为PDF:使用html2pdf.js将HTML转换为PDF
如果想要相同的效果,也可以把前端页面直接导出转换为pdf: 运用的插件:html2pdf.js
后端文件流导出接口返回:
首先我们要安装mammoth.js和html2pdf.js
npm install mammoth jspdf
代码:
// 引入
import mammoth from "mammoth";
import html2pdf from "html2pdf.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");
// 可以给pdf自定义添加样式(将word提取html再转换成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);
// 使用html2pdf.js将HTML转换为PDF
html2pdf()
.from(div)
.set({
html2canvas: { scale: 2 },
jsPDF: { format: "a4", orientation: "portrait" },
css: css,
})
.save("document.pdf");
// 清理 - 移除添加的div
document.body.removeChild(div);
})
.catch((err) => {
console.error(err);
});
};
reader.readAsArrayBuffer(res);
}
});
} catch (error) {
console.error("err", error);
}
}
第二种前端思路:把前端页面直接导出转换为pdf
页面:点击导出直接导出为pdf
<el-button type="primary" :loading="isLoading" @click="handleExport">
导 出
</el-button>
function handleExport() {
html2pdf().set({
html2canvas: { scale: 3 }, // 增加缩放比例以提高清晰度
jsPDF: { unit: 'in', format: 'a4', orientation: 'portrait' } // 设置单位和纸张大小
}).from(document.getElementById('pdfRef')).save('健康体检通知书.pdf');
}