使用html2canvas截圖不全問題的解決辦法
實現(xiàn)方法
利用 html2canvas 工具將html轉(zhuǎn)為圖片流 npm install html2canvas
利用 jspdf 工具 將圖片流轉(zhuǎn)為 pdf 并保存 npm install jspdf
遇見問題
1、截圖不全
之前沒用過這個,網(wǎng)上找了代碼之后發(fā)現(xiàn)有滾動條的情況下會截圖不全,僅能展示出當前頁面展示出來的內(nèi)容,類似于這種情況,這是帶滾動條的html,第一張和第二張分別為滾動條在頂部以及在底部的展現(xiàn)
下載成pdf之后分別為這樣,只有窗口展示的部分,滾動條以外的內(nèi)容沒有
百度之后有讓改參數(shù)的,也有讓滾動條滾至頂部的,感覺都不是我的問題,直覺說是元素高度哪里有問題,原來的頁面元素是這么寫的,對比下載后的文件,內(nèi)容高度大概和最外面的div高度是一樣的,外面盒子的高度又是固定的,本人就試了下在里面再加一個div,且不設(shè)置高度,讓其高度完全由內(nèi)容撐開,問題就解決了
<div class="red-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è)置放大的倍數(shù) // height: targetDom.clientHeight, // 網(wǎng)上原來的設(shè)置,沒用,注釋掉了 // width: targetDom.clientWidth, // 網(wǎng)上原來的設(shè)置,沒用,注釋掉了 // windowHeight: targetDom.clientHeight, // 網(wǎng)上原來的設(shè)置,沒用,注釋掉了 }).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轉(zhuǎn)圖片數(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;
總結(jié)
到此這篇關(guān)于使用html2canvas截圖不全問題的解決辦法的文章就介紹到這了,更多相關(guān)html2canvas截圖不全問題內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于javascript實現(xiàn)彩票隨機數(shù)生成(升級版)
這篇文章主要為大家詳細介紹了基于javascript實現(xiàn)彩票隨機數(shù)生成的相關(guān)資料,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-01-01JavaScript實現(xiàn)簡易tab欄切換內(nèi)容欄
這篇文章主要為大家詳細介紹了JavaScript實現(xiàn)簡易tab欄切換內(nèi)容欄,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-05-05