页面导出为PDF文件时为每页增加页眉
作者:互联网
接上篇文章,https://blog.51cto.com/boytnt/2324214,有人问到如何给每页加页眉,其实思想很简单,比如页眉上想添加logo,那就在jspdf创建每页时多加个图片上去就好了。
先上效果图,借华为LOGO一用:
再放代码,主体还是上篇文章的分页导出算法:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>测试PDF导出</title> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="js/html2canvas.min.js"></script> <script src="js/jspdf.min.js"></script> <style> html,body { margin:0; padding:0; } #page ul { padding:0;list-style:none; } #page li { line-height:110px;color:#fff;padding-left:10px;font-size:26px; } #logo { display:none; } .c0 { background-color:#ea644a; } .c1 { background-color:#f1a325; } .c2 { background-color:#38b03f; } .c3 { background-color:#03b8cf; } .c4 { background-color:#bd7b46; } .c5 { background-color:#8666b8; } </style> <script> function exportPdf() { var element = document.getElementById("page"); html2canvas(element, { logging:false }).then(function(canvas) { var pdf = new jsPDF('p', 'mm', 'a4');//A4纸,纵向 var ctx = canvas.getContext('2d'), a4w = 190, a4h = 257,//A4大小,210mm x 297mm,四边各保留10mm的边距,显示区域190x277 imgHeight = Math.floor(a4h * canvas.width / a4w),//按A4显示比例换算一页图像的像素高度 renderedHeight = 0; var logo = document.getElementById("logo");//放在页眉的图标 while(renderedHeight < canvas.height) { var page = document.createElement("canvas"); page.width = canvas.width; page.height = Math.min(imgHeight, canvas.height - renderedHeight);//可能内容不足一页 //用getImageData剪裁指定区域,并画到前面创建的canvas对象中 page.getContext('2d').putImageData(ctx.getImageData(0, renderedHeight, canvas.width, Math.min(imgHeight, canvas.height - renderedHeight)), 0, 0); //添加图像到页面,保留10mm/20mm边距 pdf.addImage(page.toDataURL('image/jpeg', 1.0), 'JPEG', 10, 20, a4w, Math.min(a4h, a4w * page.height / page.width)); //添加页眉logo pdf.addImage(logo, 'PNG', 5, 3); renderedHeight += imgHeight; if(renderedHeight < canvas.height) pdf.addPage();//如果后面还有内容,添加一个空页 delete page; } pdf.save('content.pdf'); }); } function generateData() { var html = []; html[html.length] = '<ul>'; for(var i = 0;i < 20;++i) { html[html.length] = '<li class="c'; html[html.length] = i % 6; html[html.length] = '">这是第'; html[html.length] = i; html[html.length] = '行</li>'; } html[html.length] = '</ul>'; document.getElementById('page').innerHTML = html.join(''); } </script> </head> <body onload="generateData()"> <button onclick="exportPdf()">导出pdf</button> <div id="page"></div> <img id="logo" src="huawei.png" /> </body> </html>
变化在于以下几点:
1、添加了一个隐藏的<img>标签,用于承载logo;
2、创建每一页时,多加了一行pdf.addImage(logo, 'PNG', 5, 3),用于在页眉位置放logo;
不使用<img>标签,在代码里直接创建Image对象然后指定src来加载图片也行,但要注意应在Image对象的onload事件里再处理后续代码。另外注意运行时不能直接双击打开,需要放到web服务器上,因为加载了图片资源,受浏览器安全性限制,toDataURL仅允许同源资源,否则会报错。
标签:color,html,页眉,background,logo,var,PDF,时为 来源: https://blog.51cto.com/boytnt/2479378