在 Vue 中,將 html 內容導出爲 PDF

需要用到兩個插件:html2canvasjsPDF

npm install html2canvas
npm install jspdf --save
import html2canvas from 'html2canvas';

// download()爲下載按鈕綁定的方法
download() {
   // 下面的"print"爲需要導出內容的id(把想導出的html內容用div包起來,加上id="print"即可)
   html2canvas(document.getElementById("print")).then(function(canvas) {
   	 // 此時這個canvas即選中的需要轉換的html的canvas形式
   	 // document.body.appendChild(canvas); // 這句的意思是把canvas內容再加在當前頁面內容的後面
   	 
     var url = canvas.toDataURL();
     
     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,595.28],html頁面生成的canvas在pdf中圖片的寬高
     var imgWidth = 595.28;
     var imgHeight = (592.28 / contentWidth) * contentHeight;

     var pdf = new jsPDF("", "pt", "a4");

     if (leftHeight < pageHeight) {
       pdf.addImage(url, "JPEG", 0, 0, imgWidth, imgHeight);
     } else {
       // 分頁
       while (leftHeight > 0) {
         pdf.addImage(url, "JPEG", 0, position, imgWidth, imgHeight);
         leftHeight -= pageHeight;
         position -= 841.89;
         
         //避免添加空白頁
         if (leftHeight > 0) {
           pdf.addPage();
         }
       }
     }
     
     pdf.save("xxx.pdf");
   });
 }



參考:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章