主要是通过和他们和她们html2canvas与jsPDF这两个库来实现
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><script src="https://cdn.jsdelivr.net/npm/html2canvas@1.0.0-rc.7/dist/html2canvas.min.js"></script><script src="https://cdn.bootcss.com/jspdf/1.3.4/jspdf.debug.js"></script><style>div{height: 3366px;}</style></head><body><button id="exportToPdf">导出为pdf</button><div id="export_content"><img src="http://www.mjjq.com/pic/20070425/20070425014215558.jpg" alt="" height="3366" width="800"></div><script>var downPdf = document.getElementById("exportToPdf")downPdf.onclick = function(){html2canvas(document.getElementById("export_content"), {onrendered:function(canvas) {var contentWidth = canvas.width;var contentHeight = canvas.height;//一页pdf显示html页面生成的canvas高度;var pageHeight = contentWidth / 592.28 * 841.89;//未生成pdf的html页面高度var leftHeight = contentHeight;//页面偏移var position = 0;//a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高var imgWidth = 595.28;var imgHeight = 592.28/contentWidth * contentHeight;返回一个包含图片展示的 data URI 。可以使用 type 参数其类型,默认为 PNG 格式。图片的分辨率为96dpi。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', 0, 0, imgWidth, imgHeight );} else {while(leftHeight > 0) {pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)leftHeight -= pageHeight;position -= 841.89;//避免添加空白页if(leftHeight > 0) {//jsPDF提供了一个很有用的API,addPage(),我们可以通过pdf.addPage(),来添加一页pdf,然后通过pdf.addImage(...),将图片赋予这页pdf来显示。pdf.addPage();}}}pdf.save('content.pdf');},//将背景色设置为白色(默认背景为黑色)background:"#fff"})}</script></body></html>
github上有一篇文章说明比较详细,还有具体的demo:https://github.com/linwalker/render-html-to-pdf
// 三个参数,第一个方向,第二个尺寸,第三个尺寸格式var doc = new jsPDF('landscape','pt',[205, 155])// 将图片转化为dataUrlvar imageData = ‘data:image/png;base64,iVBORw0KGgo...’;//设置字体大小doc.setFontSize(20);//10,20这两参数控制文字距离左边,与上边的距离doc.text('Stone', 10, 20);// 0, 40, 控制文字距离左边,与上边的距离doc.addImage(imageData, 'PNG', 0, 40, 205, 115);doc.save('a4.pdf')
最后附上几个jsPDF的官方网址:
http://rawgit.com/MrRio/jsPDF/master/
http://rawgit.com/MrRio/jsPDF/master/docs/index.html
http://mrrio.github.io/
