jspdf.js 如何将 html 元素 转为pdf,并且跨页文字自动换行

使用 jspdf 可以将 HTML 转换为 PDF。

引入 jspdf.js 库

yarn add jspdf

j s 代码实现

// 引入jsPDF库和PDF.js库
import jsPDF from 'jspdf';

// 获取HTML字符串
const htmlStr = '<h1>Hello, World!</h1>';
// 添加页脚
const addFooters = (doc) => {
    const pageCount = doc.internal.getNumberOfPages();
    doc.setFontSize(12);
    for (let i = 1; i <= pageCount; i++) {
        doc.setPage(i);
        doc.text(`- ${String(i)} - `, doc.internal.pageSize.width / 2, doc.internal.pageSize.height - 25, { align: 'center' });
    }
};
// 创建PDF文档
const generatePDF = () => {
    //获取元素
    const element = document.createElement('div');
    element.innerHTML = htmlStr;
    //创建pdf文件
    const doc = new jsPDF('p', 'pt', 'a4');
    // 设置边距
    const margin = {
        top: 60, right: 60, bottom: 60, left: 60
    };
    // 计算实际页面宽度和高度
    const pdfWidth = doc.getPageWidth();
    const pageWidth = pdfWidth - margin.left - margin.right;
    const pageHeight = doc.getPageHeight() - margin.top - margin.bottom;
    doc.html(element, {
            callback(pdf) {
                // 添加页脚
                addFooters(pdf);
                const file = pdf.output(type);
            },
            autoPaging: 'text',//设置跨页自动换行
            windowWidth: pdfWidth,
            width: pageWidth,
            height: pageHeight,
            margin: [margin.top, margin.right, margin.bottom, margin.left]
     });
}

如果你的html 元素中有中文,需要导入 中文字体文件

关于jspdf 如何 引入 中文字体库,参考:https://www.bbsmax.com/A/D854QVmxdE/

引入字体文件后,修改代码;

// 引入jsPDF库和PDF.js库
import jsPDF from 'jspdf';

// 导入字体文件
import './assets/siyuan-normal.js';

// 获取HTML字符串
const htmlStr = '<h1>Hello, World!</h1>';

// 创建PDF文档
const generatePDF = () => {
    //获取元素
    const element = document.createElement('div');
    //在html 元素中将字体写入样式
    element.style.fontFamily = "siyuan";
    element.innerHTML = htmlStr;
    //创建pdf文件
    const doc = new jsPDF('p', 'pt', 'a4');
    // 设置边距
    const margin = {
        top: 60, right: 60, bottom: 60, left: 60
    };
    // 计算实际页面宽度和高度
    const pdfWidth = doc.getPageWidth();
    const pageWidth = pdfWidth - margin.left - margin.right;
    const pageHeight = doc.getPageHeight() - margin.top - margin.bottom;
    doc.html(element, {
            callback(pdf) {
                // 添加页脚
                addFooters(pdf);
                const file = pdf.output(type);
            },
            autoPaging: 'text',//设置跨页自动换行
            windowWidth: pdfWidth,
            width: pageWidth,
            height: pageHeight,
            margin: [margin.top, margin.right, margin.bottom, margin.left]
     });
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值