jsp網(wǎng)站建設期末作業(yè)廣州疫情最新情況
代碼如下,直接粘貼復制即可,代碼中 jspdf 是全局引入,你可以自己局部引入
別人使用標簽的方式來顯示 base64,但是當頁面過長時,base64 大小過大會導致頁面解析異常,顯示白屏
import html2canvas from 'html2canvas';export function printPdf(dom: HTMLElement | null) {// 1 dom 存在if (!dom) return;// 2 生成 canvashtml2canvas(dom, { useCORS: true, allowTaint: true }).then(function (canvas) {// document.body.appendChild(canvas);// return;// 1 canvas 寬高const contentWidth = canvas.width;const contentHeight = canvas.height;console.log('contentWidth contentHeight', contentWidth, contentHeight);// 2 一頁 pdf 顯示 html 頁面生成的 canvas 高度const pageHeight = (contentWidth / 592.28) * 841.89;// 3 未生成 pdf 的 html 頁面高度let leftHeight = contentHeight;// 4 pdf 頁面偏移let position = 0;// 5 a4紙的尺寸 [595.28, 841.89],html 頁面生成的 canvas 在 pdf 中圖片的寬高const imgWidth = 595.28;const imgHeight = (592.28 / contentWidth) * contentHeight;const img = canvas.toDataURL('image/jpeg', 1.0);const pdf = new jspdf.jsPDF('', 'pt', 'a4');// 有兩個高度需要區(qū)分,一個是html頁面的實際高度,和生成 pdf 的頁面高度(841.89)// 當內(nèi)容未超過 pdf 一頁顯示的范圍,無需分頁if (leftHeight < pageHeight) {pdf.addImage(img, 'JPEG', 0, 0, imgWidth, imgHeight);} else {while (leftHeight > 0) {console.log(imgWidth, imgHeight, position, leftHeight);pdf.addImage(img, 'JPEG', 0, position, imgWidth, imgHeight);leftHeight -= pageHeight;position -= 841.89;// 避免添加空白頁if (leftHeight > 0) {pdf.addPage();}}}// 6 掛載至頁面const blob = dataURLtoBlob(pdf.output('datauristring'));console.log(blob);const url = window.URL.createObjectURL(blob); //獲得一個pdf的url對象location.href = url;// window.open(url, '_blank')//打開一個新窗口// console.log(url);// URL.revokeObjectURL(url) //釋放內(nèi)存// const base64String = btoa(pdf.output());// const embed = `<embed type="application/pdf" src="data:application/pdf;base64, ${base64String}" width="100%" height="100%">`;// document.documentElement.style.overflow = 'hidden';// document.body.innerHTML = embed;});
}