【jspdf】前端html生成pdf的两种办法 以及 引入中文字体
warning:
这篇文章距离上次修改已过190天,其中的内容可能已经有所变动。
在前端生成PDF文件,可以使用jsPDF库。以下是两种常见的方法:
方法一:使用html2canvas将HTML转换为canvas,然后再将canvas转为图片。
方法二:使用html2pdf.js直接将HTML转为PDF。
引入中文字体,需要使用自定义字体或者将中文转为图片。
以下是具体的实现方式:
方法一:使用html2canvas将HTML转换为canvas,然后再将canvas转为图片。
//引入jsPDF
import jsPDF from 'jspdf';
//引入html2canvas
import html2canvas from 'html2canvas';
function downloadPDF() {
const element = document.body; // 需要转换的DOM元素
html2canvas(element).then((canvas) => {
// 新建PDF文档,并添加图片
const pdf = new jsPDF('p', 'mm', 'a4');
const img = canvas.toDataURL('image/png');
pdf.addImage(img, 'PNG', 0, 0, 210, 297);
pdf.save('download.pdf'); // 保存
});
}
方法二:使用html2pdf.js直接将HTML转为PDF。
//引入jsPDF
import jsPDF from 'jspdf';
//引入html2pdf.js
import html2pdf from 'html2pdf.js';
function downloadPDF() {
const element = document.body; // 需要转换的DOM元素
html2pdf().set({
html2canvas: {
scale: 2, // 提高分辨率
dpi: 192, // 打印质量
letterRendering: true, // 使用更佳的文字渲染
},
jsPDF: {
unit: 'mm',
format: 'a4',
orientation: 'portrait' // 方向
}
}).from(element).save();
}
引入中文字体,可以使用jspdf的addFont方法,但是需要字体文件,并且需要将字体转为base64。
//引入自定义字体
import 'jspdf/dist/polyfills.js';
import font from 'jspdf/dist/standard_fonts/font.js';
import fontBase64 from '../path/to/font.base64'; // 中文字体的base64
// 添加自定义字体
font.addFont('中文字体', 'normal', 'normal', fontStyle.normal, fontWeight.normal, [fontBase64]);
// 使用自定义字体
const pdf = new jsPDF('p', 'mm', 'a4');
pdf.setFont('中文字体');
pdf.text('你好,世界!', 10, 20);
pdf.save('download.pdf');
由于中文字体较大,通常采用将中文字体转为图片的方式来解决。
//引入jsPDF
import jsPDF from 'jspdf';
// 创建canvas
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// 设置字体样式
ctx.font = '20px 微软雅黑';
// 设置字体颜色
ctx.fillStyle = '#000';
// 绘制文本
ctx.fillText('你好,世界!', 0, 20);
// 将canvas转为图片
const img = new Image();
img.src = canvas.toDataURL('image/png');
const pdf = new jsPDF('p', 'mm', 'a4');
pdf.addImage(img, 'PNG', 10, 10, 50, 20);
pdf.save('download.pdf');
以上就是使用jspdf生成PDF文件的两种方法以及引入中文字
评论已关闭