欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 资讯 > vue3.0将后端返回的word文件流转换为pdf并导出+html2pdf.js将页面导出为pdf

vue3.0将后端返回的word文件流转换为pdf并导出+html2pdf.js将页面导出为pdf

2025/6/30 20:09:15 来源:https://blog.csdn.net/lqlq54321/article/details/145844361  浏览:    关键词: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转换为PDFhtml2pdf().from(div).set({html2canvas: { scale: 2 },jsPDF: { format: "a4", orientation: "portrait" },css: css,}).save("document.pdf");// 清理 - 移除添加的divdocument.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');
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词