功能背景
一个内部简历系统,需要下载简历的功能。 页面的元素包含文本、图片(头像)、echart图表。 因为客户要求批量下载,一般来说后端生成文件流提供给前端下载,但经过几次评估,Java后端不愿意做。所以尝试前端生成文件直接导出PDF。
需求有变动,需要改为下载EXCEL格式(可能一开始就没说明白,中途产品业务还离职了)
尝试了一下,使用xlsx无法设置字体大小和单元格背景色。 可能需要xlsx-style,目前项目安装依赖后运行时有报错需要处理。 xlsx-node似乎不能在前端使用。
使用的依赖包安装
npm i html2canvas
npm i JsPDF
html代码
<iframe
v-if="isEdit"
style="position: absolute; left: 9990px;"
id='frameOne'
:key="fkey"
:src="currentResume"
width="1432px"
height="999px"
frameborder="0"
allowfullscreen
:onload="iframeLoaded"
></iframe>
JS代码
const iframe = document.querySelector('#frameOne')
var iframeWindow = iframe.contentWindow
var iframeDocument = iframeWindow.document
const fn = iframeDocument.querySelector('#employeeName')?.textContent
if (!fn || fn === 'undefined') {
return ElMessage.warning('请等待数据加载完成后重试!')
}
// 本地环境无法跨域图片下载
const canvas = await html2canvas(iframeDocument.body, {
useCORS: true, // 【重要】开启跨域配置
scale: window.devicePixelRatio < 3 ? window.devicePixelRatio : 2,
allowTaint: true
})
if (canvas) {
var contentWidth = canvas.width
var contentHeight = canvas.height
var pdfWidth = (contentWidth + 10) / 2
var pdfHeight = (contentHeight + 10) / 2// 500为底部留白
var imgWidth = pdfWidth - 20
var imgHeight = pdfHeight // 内容图片这里不需要留白的距离
var pageData = canvas.toDataURL('image/jpeg', 1.0)
var pdf = new JsPDF('', 'pt', [pdfWidth, pdfHeight])
pdf.addImage(pageData, 'jpeg', 10, 10, imgWidth, imgHeight)
pdf.save(`${fn}的简历.pdf`)
}
关于iframe的使用
平时很少使用,iframe的src可以开头/路径的方式使用当前环境
例如:/portal/index.html#/resume?id=123
批量也就是前端for列表渲染多个iframe,for调用html2canvas,后端不愿支持,前端做好功能就不错忽略性能吧。
使用遇到的问题
页面包含图片需要解决跨域问题,
如上设置CORS入参并且为
img标签添加crossorigin="anonymous"属性并没有解决
这里因为是用户头像,文件不大所以最后的方案是要后端返回base64。