vue技術棧導出pdf


1 、添加兩個模塊

// 第一個.將頁面html轉換成圖片
npm install --save html2canvas 
// 第二個.將圖片生成pdf
npm install jspdf --save  

2、定義全局函數,創建一個htmlToPdf.js文件在指定位置.例如放在('src/utils/htmlToPdf')

// 導出頁面為PDF格式
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
export default{
install (Vue, options) {
Vue.prototype.getPdf = function (htmlTitle,currentTime) {
var element = document.getElementById("pdfDom");
html2canvas(element, {
logging:false
}).then(function(canvas) {
var pdf = new jsPDF('p', 'mm', 'a4'); //A4紙,縱向
var ctx = canvas.getContext('2d'),
a4w = 190, a4h = 277, //A4大小,210mm x 297mm,四邊各保留10mm的邊距,顯示區域190x277
imgHeight = Math.floor(a4h * canvas.width / a4w), //按A4顯示比例換算一頁圖像的像素高度
renderedHeight = 0;

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);
pdf.addImage(page.toDataURL('image/jpeg', 1.0), 'JPEG', 10, 10, a4w, Math.min(a4h, a4w * page.height / page.width)); //添加圖像到頁面,保留10mm邊距

renderedHeight += imgHeight;
if(renderedHeight < canvas.height)
pdf.addPage();//如果后面還有內容,添加一個空頁
// delete page;
}
pdf.save(htmlTitle + currentTime );
});
}
}
}

3、在main.js中使用我們定義的函數文件。

import htmlToPdf from 'src/utils/htmlToPdf'
Vue.use(htmlToPdf)

4、在需要的導出的頁面..調用我們的getPdf方法即可.

<div class="row" id="pdfDom" style="padding-top: 55px;background-color:#fff;">
    //給自己需要導出的ui部分.定義id為"pdfDom".此部分將就是pdf顯示的部分
</div>
<button type="button" class="btn btn-primary"v-on:click="getPdf()">導出PDF</button>

js   頁面導出PDF文件名

export default {
  data () {
      return {
      htmlTitle: '頁面導出PDF文件名'
      }
  }
 }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM