前端页面转pdf

首先,需要安装两个库
  1. html2canvas
  2. jspdf

先引入这个公用的html转pdf的方法

javascript 复制代码
/**
	path:src/utils/htmlToPdf.js
	name:导出页面为pdf格式
**/
import html2Canvas from "html2canvas@1.4.1";
import JsPDF from "jspdf@2.5.1";

const htmlToPdf  = {
    getPdf(title) {
        html2Canvas(document.querySelector('#pdfDom'), {
            allowTaint:true,
        }).then((canvas) => {
            //内容的宽度
            let contentWidth = canvas.width;
            //内容高度
            let contentHeight = canvas.height;
            //一页pdf显示html页面生成的canvas高度,a4纸的尺寸(595.28,841.89)
            let pageHeight = (contentWidth / 592.28) *  841.89;
      		//未生成pdf的html页面高度
            let leftHeight = contentHeight;
            //页面偏移
            let position = 0;
            //a4纸的尺寸(595.28,841.89),html页面生成的canvas在pdf中图片的宽高
            let imgWidth = 595.28 ;
            let imgHeight = (592.28 / contentWidth) * contentHeight;
            //canvas转图片数据
            let pageData = canvas.toDataURL("image/jpeg",1.0) ;
            //新建JsPDF对象(a:横线排列还是竖向排列,b:单位,c:a4纸)
            let PDF = new JsPDF("","pt","a4")
            
            debugger;
            
            //判断是否分页
            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();
                    }
                }
            }
            //保存文件
            PDF.save(title + ".pdf")
        });
    }
};
export default htmlToPdf;
相关推荐
C澒8 分钟前
前端分层架构实战:DDD 与 Clean Architecture 在大型业务系统中的落地路径与项目实践
前端·架构·系统架构·前端框架
BestSongC11 分钟前
行人摔倒检测系统 - 前端文档(1)
前端·人工智能·目标检测
0思必得044 分钟前
[Web自动化] Selenium处理滚动条
前端·爬虫·python·selenium·自动化
Misnice1 小时前
Webpack、Vite、Rsbuild区别
前端·webpack·node.js
青茶3601 小时前
php怎么实现订单接口状态轮询(二)
前端·php·接口
大橙子额2 小时前
【解决报错】Cannot assign to read only property ‘exports‘ of object ‘#<Object>‘
前端·javascript·vue.js
爱喝白开水a3 小时前
前端AI自动化测试:brower-use调研让大模型帮你做网页交互与测试
前端·人工智能·大模型·prompt·交互·agent·rag
董世昌413 小时前
深度解析ES6 Set与Map:相同点、核心差异及实战选型
前端·javascript·es6
吃杠碰小鸡4 小时前
高中数学-数列-导数证明
前端·数学·算法
kingwebo'sZone4 小时前
C#使用Aspose.Words把 word转成图片
前端·c#·word