寫在前面: 為了不浪費你們的時間,預先說明:由于時間關系本次使用jquery2x.js+html2canvas +html2canvas.js+ jsPdf.debug.js 組成寫在elementUI中,簡單做一下文檔總結
檔案下載下傳位址:https://download.csdn.net/download/qq_27751965/19476359
重點:需要導出節點的内容不能滾動,高度需auto
Html:
<!--點選按鈕-->
<div style="position: fixed;right: 40px;top:40%;z-index: 4;cursor: pointer;display: none" id="exportToPdfBtn">
<el-button type="primary" plain size="mini" id="exportToPdf" ><i class="iconfont iconxiazai" style="font-size: 12px">導出為PDF</i></el-button>
</div>
<!--導出文本容器-->
<div id="pdfDom" >
<div id='part1'>...</div>
<div id='part2'>...</div>
<div id='part3'>...</div>
.......
</div>
Css:
/**
**主要說明容器得高度不能固定,要麼會隻列印它高度顯示得部分
**/
#pdfDom {
padding: 15px;
background-color: #ffffff;
overflow-y: auto;
height:auto;
}
Js:
var that = this;
var downPdf = document.getElementById("exportToPdf");
downPdf.onclick = function() {
// 進行dom截圖 必須讓dom更新完再調用
Vue.nextTick(()=>{
var targetDom = $("#pdfDom");
// 設定 前三個部分各占一個頁面 頁面高度 = 目前寬度 + 30(頁面15padding) / 552.28去掉canvas20padding * 列印高度
$('#part1').css('height', (targetDom.width() + 30) / 552.28 * 841.89)
$('#part2').css('height', (targetDom.width() + 30) / 552.28 * 841.89)
$('#part3').css('height', (targetDom.width() + 30) / 552.28 * 841.89)
$('#wellCon').scrollTop(0);
var copyDom = targetDom.clone();
copyDom.attr('id','content');
// copyDom.css('display','none');
copyDom.width(targetDom.width() + "px");
copyDom.height(targetDom.height() + "px");
$('body').append(copyDom)
html2canvas(targetDom, {
allowTaint: true,
useCORS: true,
// background:"#fff",
// dpi: 192,//導出pdf清晰度
// scale:2,
}).then((canvas)=>{
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,841.89],html頁面生成的canvas在pdf中圖檔的寬高
var imgWidth = 555.28;
var imgHeight = 555.28/contentWidth * contentHeight;
var pageData = canvas.toDataURL('image/jpeg', 1.0);
// 取消生成狀态
this.isLoading = false
var pdf = new jsPDF('', 'pt', 'a4');
//有兩個高度需要區分,一個是html頁面的實際高度,和生成pdf的頁面高度(841.89)
//當内容未超過pdf一頁顯示的範圍,無需分頁
if (leftHeight < pageHeight) {
imgWidth = 555.28;
imgHeight = 555.28/contentWidth * contentHeight;
pdf.addImage(pageData, 'JPEG', 20, 20, imgWidth, imgHeight );
} else {
while(leftHeight > 0) {
leftHeight -= pageHeight;
pdf.addImage(pageData, 'JPEG', 20, position, imgWidth, imgHeight)
position -= 841.89;
//避免添加空白頁
if(leftHeight > 0) {
pdf.addPage();
}
}
}
pdf.save(that.deptName + '-' + that.userInfo.user_name + '-' + that.endTime + '.pdf');
setTimeout(() => {window.close()},100)
// 儲存pdf對象
})
})
}
說明:新增功能-------前三塊内容設定單頁顯示(下載下傳包沒有,算法)
// 設定 前三個部分各占一個頁面 頁面高度 = 目前寬度 + 30(頁面15padding) / 552.28去掉canvas20padding * 列印高度
$('#part1').css('height', (targetDom.width() + 30) / 552.28 * 841.89)
$('#part2').css('height', (targetDom.width() + 30) / 552.28 * 841.89)
$('#part3').css('height', (targetDom.width() + 30) / 552.28 * 841.89)
//.......