当前位置: 首页 > news >正文

使用 html2canvas 和 jspdf 将页面转 pdf,同时解决当页面过长时,页面白屏问题

代码如下,直接粘贴复制即可,代码中 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');// 有两个高度需要区分,一个是html页面的实际高度,和生成 pdf 的页面高度(841.89)// 当内容未超过 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) //释放内存// 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;});
}
http://www.lryc.cn/news/188110.html

相关文章:

  • 【Python 千题 —— 基础篇】今年几岁啦
  • git push 失败 shallow update not allowed
  • uniapp 在uni.scss 根据@mixin定义方法 、通过@include全局使用
  • C++ 类和对象(一)
  • rust函数
  • 链表的基本操作
  • Flutter AI五子棋
  • springboot项目中后台文件上传处理
  • 【SQL】MySQL中的存储引擎、事务、锁、日志
  • DRM全解析 —— CRTC详解(2)
  • 3d环形图开发(vue3+vite+ts)
  • element ui中父子组件共用一个el-dialog弹窗,切换组件页面弹窗进行关闭
  • 基于Keil a51汇编 —— Segments, Modules, and Programs
  • 基于Java+SpringBoot+Vue民宿管理系统的设计与实现 前后端分离【Java毕业设计·文档报告·代码讲解·安装调试】
  • 【Qt】三种方式实现抽奖小游戏
  • 【算法与数据结构】--算法基础--算法设计与分析
  • vue部分入门知识点代码示例
  • 【图灵】Spring为什么要用三级缓存解决循环依赖问题
  • bert入门
  • 蓝桥杯基础---切面条
  • Spring Data Redis使用方式
  • HarmonyOS/OpenHarmony原生应用开发-华为Serverless认证服务说明(二)
  • 华为数通方向HCIP-DataCom H12-831题库(多选题:241-259)
  • 深度学习在 NumPy、TensorFlow 和 PyTorch 中实现所有损失函数
  • 超低延时直播技术演进之路-进化篇
  • 相机坐标系之间的转换
  • jvm--对象实例化及直接内存
  • 【数据结构与算法】如何对快速排序进行细节优化以及实现非递归版本的快速排序?
  • 【电商API接口的应用:电商数据分析入门】初识Web API(一)
  • 大运新能源天津车展深度诠释品牌魅力 为都市人群打造理想车型