getPdf.js
import html2Canvas from 'html2canvas';
import JsPDF from 'jspdf';
/**
* @description: 導(dǎo)出pdf
* @param {String} id 攜帶跳轉(zhuǎn)的id參數(shù)
* @return:
*/
async getPdf(_this) {
let userAgent = navigator.userAgent;
// 判斷瀏覽器內(nèi)核是否是是否是火狐或IE
if (userAgent.indexOf('Firefox') > -1 || !!window.ActiveXObject || 'ActiveXObject' in window) {
alert('PDF導(dǎo)出暫不支持您的瀏覽器,請更換谷歌chrome內(nèi)核瀏覽器');
return;
}
_this.pdfExportLoading = true;
var title = _this.htmlTitle;
const pdfDom = document.querySelector('#pdfDom');
// mainFrame = document.querySelector('#mainFrame'),
// const iframeCanvas = await html2Canvas(mainFrame);
// pdfDom.appendChild(iframeCanvas);
_this.$nextTick(() => {
html2Canvas(pdfDom, {
useCORS: true
}
).then(function (canvas) {
// pdfDom.removeChild(iframeCanvas);
let contentWidth = canvas.width;
let contentHeight = canvas.height;
let pageHeight = contentWidth / 592.28 * 841.89;
let leftHeight = contentHeight;
let position = 0;
let imgWidth = 595.28;
let imgHeight = 592.28 / contentWidth * contentHeight;
let pageData = canvas.toDataURL('image/jpeg', 1.0);
let PDF = new JsPDF('', 'pt', 'a4');
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) {
PDF.addPage();
}
}
}
PDF.save(title + '.pdf');
_this.pdfExportLoading = false;
}
);
});
}
組件中標(biāo)注某個元素 id="pdfDom" 此標(biāo)注元素做為html2Canvas方法中的第一個參數(shù),
pdfExportLoading、htmlTitle導(dǎo)出文件名
<div class="table-page-search-wrapper" id="pdfDom">
....
data() {
return {
htmlTitle:"",
pdfExportLoading: false
}
}
調(diào)用 傳入當(dāng)前實例對象 至于方法掛在哪 自由決定
getPdf(this)