文章詳情頁
使用html2canvas截圖不全問題的解決辦法
瀏覽:3日期:2022-06-13 10:38:28
目錄實現(xiàn)方法遇見問題具體封裝代碼總結實現(xiàn)方法
利用 html2canvas 工具將html轉為圖片流 npm install html2canvas利用 jspdf 工具 將圖片流轉為 pdf 并保存npm install jspdf
遇見問題1、截圖不全
之前沒用過這個,網(wǎng)上找了代碼之后發(fā)現(xiàn)有滾動條的情況下會截圖不全,僅能展示出當前頁面展示出來的內(nèi)容,類似于這種情況,這是帶滾動條的html,第一張和第二張分別為滾動條在頂部以及在底部的展現(xiàn)
下載成pdf之后分別為這樣,只有窗口展示的部分,滾動條以外的內(nèi)容沒有
百度之后有讓改參數(shù)的,也有讓滾動條滾至頂部的,感覺都不是我的問題,直覺說是元素高度哪里有問題,原來的頁面元素是這么寫的,對比下載后的文件,內(nèi)容高度大概和最外面的div高度是一樣的,外面盒子的高度又是固定的,本人就試了下在里面再加一個div,且不設置高度,讓其高度完全由內(nèi)容撐開,問題就解決了
<div id='pdfDom_children'> // 這里是滾動的div <div class='first-div'></div> <div class='second-div'></div> <div>111</div> </div>修改后的頁面元素
<div class='red-div'> <div id='pdfDom_children'><div class='first-div'></div><div class='second-div'></div><div>111</div> </div></div>具體封裝代碼// 導出頁面為PDF格式import html2canvas from 'html2canvas';import JsPDF from 'jspdf';const htmlToPdf = { getPdf(title: string) { const targetDom = document.getElementById('pdfDom_children'); html2canvas(document.querySelector('#pdfDom_children'), { allowTaint: true, backgroundColor: 'white', useCORS: true, //支持圖片跨域 scale: 1, //設置放大的倍數(shù) // height: targetDom.clientHeight, // 網(wǎng)上原來的設置,沒用,注釋掉了 // width: targetDom.clientWidth, // 網(wǎng)上原來的設置,沒用,注釋掉了 // windowHeight: targetDom.clientHeight, // 網(wǎng)上原來的設置,沒用,注釋掉了 }).then((canvas) => { //內(nèi)容的寬度 const contentWidth = canvas.width; //內(nèi)容的高度 const contentHeight = canvas.height; //一頁pdf顯示htm1頁面生成的canvas高度,a4紙的尺寸[595.28,841.89]; const pageHeight = (contentWidth / 592.28) * 841.89; //未生成pdf的htm1頁面高度 let leftHeight = contentHeight; //頁面偏移 let position = 0; //a4紙的尺寸[595.28,841.89],htm1頁面生成的canvas在pdf中圖片的寬高 const imgwidth = 595.28; const imgHeight = (592.28 / contentWidth) * contentHeight; //canvas轉圖片數(shù)據(jù) const pageData = canvas.toDataURL('img/jpeg', 1.0); //新建JSPDF對象 const 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(); }} } console.log(pageData); //保存文件 PDF.save(title + '.pdf'); }); },};export default htmlToPdf;總結到此這篇關于使用html2canvas截圖不全問題的解決辦法的文章就介紹到這了,更多相關html2canvas截圖不全問題內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持好吧啦網(wǎng)!
標簽:
JavaScript
排行榜
