接上篇文章,http://www.javashuo.com/article/p-ahecubtu-ky.html,有人問到如何給每頁加頁眉,其實思想很簡單,好比頁眉上想添加logo,那就在jspdf建立每頁時多加個圖片上去就行了。html
先上效果圖,借華爲LOGO一用:web
再放代碼,主體仍是上篇文章的分頁導出算法:算法
<!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,上下保留20mm的邊距,顯示區域190x257 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>
變化在於如下幾點:canvas
一、添加了一個隱藏的<img>標籤,用於承載logo;
二、建立每一頁時,多加了一行pdf.addImage(logo, 'PNG', 5, 3),用於在頁眉位置放logo;瀏覽器
不使用<img>標籤,在代碼裏直接建立Image對象而後指定src來加載圖片也行,但要注意應在Image對象的onload事件裏再處理後續代碼。另外注意運行時不能直接雙擊打開,須要放到web服務器上,由於加載了圖片資源,受瀏覽器安全性限制,toDataURL僅容許同源資源,不然會報錯:Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.。安全