使用 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]
});
}