公司 做網(wǎng)站推廣信息發(fā)布平臺
之前在弄頁面導(dǎo)出為pdf的時候,jspdf配合html2canvas貌似很好用,我自己在使用的時候也沒有覺得有什么問題,但是客戶那邊反饋說下載下來的pdf不全. 后來問了客戶才發(fā)現(xiàn)客戶的瀏覽器比例縮放到了125%;這就導(dǎo)致了pdf不全, 先看看原來的代碼:
download() {let jsPDF = jspdf.jsPDF;let container = document.getElementById('reportContent');let boundingClientRect = container.getBoundingClientRect();let width = boundingClientRect.width;let height = boundingClientRect.height;let canvas = document.createElement('canvas');let scale = 2; //這里放大了2倍是為了讓導(dǎo)出的pdf更加清晰.canvas.width = width * scale;canvas.height = height * scale;let context = canvas.getContext('2d');context.scale(scale , scale); //這里需要放大html2canvas(container, {allowTaint: true,taintTest: true,canvas,}).then(canvas => {let binary = canvas.toDataURL("image/jpeg", 1)canvas.toBlob((blobObj) => {let contentWidth = canvas.width;let contentHeight = canvas.height;let pdf = new jsPDF('l', 'pt', [contentWidth, contentHeight]);pdf.addImage(binary, "JPEG", 0, 0, contentWidth, contentHeight)pdf.save('xxx.pdf');});})},
以上代碼在100%縮放的情況下沒有任何問題,導(dǎo)出的pdf也很清晰,但是一旦到了125%或者其他的縮放比例,那么導(dǎo)出的pdf就會缺失掉一部分.那么需要這么修改呢? 直接上代碼:
download() {let jsPDF = jspdf.jsPDF;let container = document.getElementById('reportContent');let boundingClientRect = container.getBoundingClientRect();let width = boundingClientRect.width;let height = boundingClientRect.height;let canvas = document.createElement('canvas');let devicePixelRatio = window.devicePixelRatio || 1;let scale = 2 * devicePixelRatio;//這里放大了2倍是為了讓導(dǎo)出的pdf更加清晰.canvas.width = width * scale;canvas.height = height * scale;let context = canvas.getContext('2d');context.scale(scale / devicePixelRatio, scale / devicePixelRatio); //這里需要放大, 同時縮小繪制, 否則會出現(xiàn)pdf不全的情況.html2canvas(container, {allowTaint: true,taintTest: true,canvas,}).then(canvas => {let binary = canvas.toDataURL("image/jpeg", 1)canvas.toBlob((blobObj) => {let contentWidth = canvas.width;let contentHeight = canvas.height;let pdf = new jsPDF('l', 'pt', [contentWidth, contentHeight]);console.log(canvas.width, canvas.height);pdf.addImage(binary, "JPEG", 0, 0, contentWidth, contentHeight)pdf.save(vthis.reportTitle + '.pdf');});})},
需要改的也不多, 只是需要判斷下設(shè)備的devicePixelRatio; 這樣就不會出現(xiàn)pdf不全的問題了;
tips:這里有個小坑, 就是html2canvas的版本需要在1.4以上;不然的話導(dǎo)出的pdf會出現(xiàn)黑邊, 之前用的是1.2版本,就出現(xiàn)了黑邊,怎么調(diào)都不對,最后換了個版本就行了.....我用的版本是1.4.1.
還有個問題是pdf里面如果有echarts的話可能會不是很清晰,這里在創(chuàng)建echarts的時候可以加個配置就可以了.
let myChart = echarts.init(document.getElementById('deviceOnlineCharts'), null, {devicePixelRatio: 2});