js生成pdf

js生成pdf

html->img->pdf

下载依赖

javascript 复制代码
npm install html2canvas
npm install jspdf

引入依赖

javascript 复制代码
import html2canvas from "html2canvas"
import jsPDF from 'jspdf';

代码

javascript 复制代码
const A4_WIDTH = 595.28
const A4_HEIGHT = 841.89
//参数 html(dom) imgsrc(封面可不加,直接加到第一个参数) fileName(文件名称)
export const handleHtml2pdf = (html, imgSrc, fileName, cb) => {
    new html2canvas(html, {
        useCORS: true,
        allowTaint: true,
    }).then(canvas => {
        var contentWidth = canvas.width;
        var contentHeight = canvas.height;
        //一页pdf显示html页面生成的canvas高度;
        var pageHeight = contentWidth / A4_WIDTH * A4_HEIGHT;
        //未生成pdf的html页面高度
        var leftHeight = contentHeight;
        //页面偏移
        var position = 0;
        //a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
        var imgWidth = A4_WIDTH;
        var imgHeight = A4_WIDTH / contentWidth * contentHeight;
        var pageData = canvas.toDataURL('image/jpeg', 1.0);
        var pdf = new jsPDF('', 'pt', 'a4');
        if (imgSrc) {
            pdf.addImage(imgSrc, 'JPEG', 0, 0, imgWidth, imgHeight);
            pdf.addPage();
        }
        if (leftHeight < pageHeight) {
            pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
        } else {
            while (leftHeight > 0) {
                //arg3-->距离左边距;arg4-->距离上边距;arg5-->宽度;arg6-->高度
                pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
                leftHeight -= pageHeight;
                position -= A4_HEIGHT;
                //避免添加空白页
                if (leftHeight > 0) {
                    pdf.addPage();
                }
            }
        }
        pdf.save(fileName || "pdf.pdf");
        cb()
    })
}
相关推荐
moshuying1 天前
别让AI焦虑,偷走你本该有的底气
前端·人工智能
GIS之路1 天前
ArcPy,一个基于 Python 的 GIS 开发库简介
前端
可夫小子1 天前
OpenClaw基础-为什么会有两个端口
前端
喝拿铁写前端1 天前
Dify 构建 FE 工作流:前端团队可复用 AI 工作流实战
前端·人工智能
喝咖啡的女孩1 天前
React 合成事件系统
前端
从文处安1 天前
「九九八十一难」组合式函数到底有什么用?
前端·vue.js
前端Hardy1 天前
面试官:JS数组的常用方法有哪些?这篇总结让你面试稳了!
javascript·面试
用户5962585736061 天前
戴上AI眼镜逛花市——感受不一样的体验
前端
yuki_uix1 天前
Props、Context、EventBus、状态管理:组件通信方案选择指南
前端·javascript·react.js
老板我改不动了1 天前
前端面试复习指南【代码演示多多版】之——HTML
前端