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

前端实现把整个页面转成PDF保存到本地(DOM转PDF)

一、问题
遇到一个需求,就是要把整个看板页面导出成PDF用在汇报,也就是要把整个DOM生成一个PDF保存到本地。

二、解决方法
1、解决思路:使用插件 jspdf 和 html2canvas,我用的版本如下图
在这里插入图片描述
2、代码实现

import  { jsPDF }  from 'jspdf'
import html2canvas from 'html2canvas'// 封装成一个公共的方法(核心代码)
export const htmlToPDF = async (htmlId: string, title: string, bgColor = "#fff") => {const pdfDom = document.getElementById(htmlId) as HTMLElement | null;if (!pdfDom) {console.error('Element not found');return '';}const scale = window.devicePixelRatio || 1; // 使用设备像素比来提高清晰度const canvas = await html2canvas(pdfDom, {scale: scale,useCORS: true,backgroundColor: bgColor,});const imgProps = canvas.toDataURL('image/png'); // 使用PNG格式提高质量const pdf = new jsPDF({orientation: 'portrait',unit: 'px',format: [595.28, 841.89], // A4尺寸(以像素为单位)});const imgPropsObj = pdf.getImageProperties(imgProps);const pdfWidth = 576; // A4宽度减去一些边距// 控制页面展示 调整这个98 防止出现空白页const pdfHeight = (imgPropsObj.height * pdfWidth) / imgPropsObj.width - 98;const pageHeight = 841.89; // A4页面的高度let heightLeft = pdfHeight; // 剩余高度let y = 0; // 当前Y坐标// 处理分页逻辑while (heightLeft > 0) {const imgHeight = Math.min(heightLeft, pageHeight); // 当前图像可显示的高度pdf.addImage(imgProps, 'PNG', 0, y, pdfWidth, imgHeight); // 添加图像heightLeft -= imgHeight; // 减去已添加的高度y += imgHeight; // 移动Y坐标if (heightLeft > 0) {pdf.addPage(); // 如果还有内容,则添加新页面}}// 生成并返回PDF文件pdf.save(title + '.pdf');const pdfUrl = window.URL.createObjectURL(new Blob([pdf.output('blob'), { type: 'application/pdf' }]));return pdfUrl;
};// 页面中调用 box:要转成pdf文件的盒子
<div id="box">
// 此处为你的页面内容
</div>
// 点击如下方法保存pdf
<button @click="fn">生产pdf</button>// htmlToPDF 第一个参数:要生成pdf文件的盒子id  第二个参数:生成pdf的文件名
const fn = ()=> {const pdfUrl = htmlToPDF("box", 'xxx.pdf')
}
http://www.lryc.cn/news/493102.html

相关文章:

  • Vue 3 学习文档(一)
  • 【适配】屏幕拖拽-滑动手感在不同分辨率下的机型适配
  • 牛客周赛 Round 69(A~E)
  • Spring Boot 实战:分别基于 MyBatis 与 JdbcTemplate 的数据库操作方法实现与差异分析
  • 【jmeter】服务器使用jmeter压力测试(从安装到简单压测示例)
  • 使用Python实现自动化邮件通知:当长时程序运行结束时
  • 框架学习07 - SpringMVC 其他功能实现
  • NAT:连接私有与公共网络的关键技术(4/10)
  • RabbitMQ2:介绍、安装、快速入门、数据隔离
  • 衡山派D133EBS 开发环境安装及SDK编译烧写镜像烧录
  • 【Spring MVC】如何获取cookie/session以及响应@RestController的理解,Header的设置
  • C++设计模式行为模式———策略模式
  • Spring Cloud 中 bootstrap.yml 配置文件详解
  • Java项目实战II基于SpringBoot前后端分离的网吧管理系统(开发文档+数据库+源码)
  • ASP网络安全讲述
  • DFS 创建分级菜单
  • HDU Go Running(最小点覆盖 + 网络流优化)
  • C++设计模式-中介者模式
  • 文件上传与下载服务 | Flask 实战
  • MySQL 中的排序:索引排序与文件排序
  • 深入理解React Hooks:使用useState和useEffect
  • AWS codebuild + jenkins + github 实践CI/CD
  • Android PMS(Package Manager Service)源码介绍
  • 运维面试整理总结
  • 图数据库 Cypher语言
  • 阿里云oss转发上线-实现不出网钓鱼
  • Spring Boot 3.4.0 发行:革新与突破的里程碑
  • 【网络安全】
  • 在SQLyog中导入和导出数据库
  • RabbitMQ简单应用