如何在jsPDF中为自定义字体指定font-stretch属性?
解决jsPDF加载带font-stretch变体的自定义字体问题
核心问题
你之前的代码把所有Bahnschrift变体都注册为同一个fontStyle: 'normal',导致jsPDF无法区分不同拉伸的字体文件,自然无法正确应用condensed/expanded变体。
修正方案
jsPDF的addFont方法允许自定义fontStyle参数值,我们可以直接将condensed和expanded作为style标识来注册对应字体,之后通过指定该style来调用对应变体。
1. 合并字体加载代码(更简洁)
将三个字体的VFS注册和字体添加合并到一个函数中,避免重复的事件监听:
import { jsPDF } from "jspdf"; // 替换为你的三个字体文件的base64编码 const bahnschriftNormal = "<base64 of bahnschrift-normal.ttf>"; const bahnschriftCondensed = "<base64 of bahnschrift-condensed.ttf>"; const bahnschriftExpanded = "<base64 of bahnschrift-expanded.ttf>"; const registerBahnschriftFonts = function () { // 注册Normal变体 this.addFileToVFS('Bahnschrift-normal.ttf', bahnschriftNormal); this.addFont('Bahnschrift-normal.ttf', 'Bahnschrift', 'normal'); // 注册Condensed变体,自定义style为'condensed' this.addFileToVFS('Bahnschrift-condensed.ttf', bahnschriftCondensed); this.addFont('Bahnschrift-condensed.ttf', 'Bahnschrift', 'condensed'); // 注册Expanded变体,自定义style为'expanded' this.addFileToVFS('Bahnschrift-expanded.ttf', bahnschriftExpanded); this.addFont('Bahnschrift-expanded.ttf', 'Bahnschrift', 'expanded'); }; // 添加字体加载事件 jsPDF.API.events.push(['addFonts', registerBahnschriftFonts]);
2. 正确使用不同变体字体
使用jsPDF内置的setFont方法直接指定字体族和对应的style,不需要依赖浏览器的document.fonts.load(这是用于网页字体,和jsPDF内部字体无关):
// 创建PDF实例 const pdf = new jsPDF(); // 使用Normal变体 pdf.setFont('Bahnschrift', 'normal'); pdf.setFontSize(16); pdf.text('这是Normal样式的Bahnschrift文本', 10, 20); // 使用Condensed变体 pdf.setFont('Bahnschrift', 'condensed'); pdf.text('这是Condensed样式的Bahnschrift文本', 10, 40); // 使用Expanded变体 pdf.setFont('Bahnschrift', 'expanded'); pdf.text('这是Expanded样式的Bahnschrift文本', 10, 60); // 保存PDF pdf.save('Bahnschrift-Variants.pdf');
关键说明
- jsPDF的
addFont第三个参数fontStyle支持自定义字符串,不局限于normal/bold/italic这类预定义值,我们可以直接用字体的拉伸属性作为style标识。 - 每个字体文件必须对应唯一的
fontFamily + fontStyle组合,这样jsPDF才能正确区分并加载对应的字体变体。 - 无需使用
document.fonts.load,因为jsPDF的字体是内部管理的,和浏览器网页字体是两个独立的系统。
内容的提问来源于stack exchange,提问作者Emilio Clemente
相关产品推荐
相关产品推荐

