【前端html页面数据导出为pdf文件】
文前白话
项目需要,将网页端查询的数据结果与数据分析结果导出文件,保存到本地。具体是两个页面分别生成文件。
在网页端导出 Excel 数据表格保存本地
- 第一个功能需要导出excel表格,可参考:
【使用SheetJS实现在网页端导出 Excel 表格保存(js-xlsx)】. - 第二个页面,涉及数据分析,网页端生成了不同颜色分析图表,为了达到保存分析数据的效果,采用了简单的方法,直接保存生成的页面图表为PDF文件,不考虑保存图表的渲染什么其他方式的复杂操作。其他的方法可参考文章末位链接的参考方法。
前端html页面数据导出为pdf文件
- 本文使用的方法:html2canvas+jsPDF
- 操作:在导出页面HTML标签出:
<div class="title action">
<img src="../static/images/icon-download.png" alt="">
<!-- <span >导出报表</span> -->
<span id="renderPdf">导出报表</span>
</div>
- javascript 部分相关代码(需要依赖spdf和html2canvas相关js文件)
<script src="{{ url_for('static', filename='html2canvas.js') }}"></script> <!-- 引入 html2canvas.js 文件 -->
<script src="{{ url_for('static', filename='jsPdf.debug.js') }}"></script> <!-- 引入 jsPdf.debug.js 文件 -->
<script src="{{ url_for('static', filename='analysis.js') }}"></script> <!-- 所在 HTML 文件对应的 js 文件,这里是放在了导出数据页面对应的HTML文件中,且引入的依赖js文件在执行页面js上面 -->
<script type="text/javascript">
var downPdf = document.getElementById("renderPdf");
downPdf.onclick = function() {
html2canvas(document.body, {
onrendered:function(canvas) {
var contentWidth = canvas.width;
var contentHeight = canvas.height;
//设置一页pdf显示html页面生成的canvas高度;
var pageHeight = contentWidth / 595.28 * 841.89;
//未生成pdf的html页面高度
var leftHeight = contentHeight;
//pdf页面偏移
var position = 0;
//a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
var imgWidth = 800;
var imgHeight = 800/contentWidth * contentHeight;
var pageData = canvas.toDataURL('image/jpeg', 1.0);
var pdf = new jsPDF('', 'pt', 'a4');
//有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
//当内容未超过pdf一页显示的范围,无需分页
if (leftHeight < pageHeight) {
pdf.addImage(pageData, 'JPEG', 20, 0, imgWidth, imgHeight );
} else {
while(leftHeight > 0) {
pdf.addImage(pageData, 'JPEG', 20, position, imgWidth, imgHeight)
leftHeight -= pageHeight;
position -= 841.89;
//避免添加空白页
if(leftHeight > 0) {
pdf.addPage();
}
}
}
pdf.save('数据分析.pdf');
}
})
}
</script>
-
依赖的 js 文件直通下载链接:
-
html2canvas.js
-
jsPdf.debug.js
链接:https://pan.baidu.com/s/12I_QABxM4ds9L6c2QvbtXA
提取码:3nfu
reference: