如何使用html方法在jsPDF中修复自定义字体的错误字母间距

3

我正在使用 .html 方法将 HTML 转换为 PDF,类似于以下内容:

 doc.html(content, {
  callback: () => {
    resolve(doc);
  },
  html2canvas: {
    scale,
    logging: true,
    letterRendering: 1,
    allowTaint: true,
    useCORS: true,
  },
  dompurify,
  margin: 0,
  fontFaces,
});

fontFaces被定义为一个对象数组,类似于以下内容(使用Google字体):

{
  family: 'Balsamiq-Sans', weight: 'normal', stretch: 'normal',
  src: [{ url: 'http://fonts.gstatic.com/s/balsamiqsans/v3/P5sEzZiAbNrN8SB3lQQX7Pnc8dkdIYdNHzs.ttf', format: 'truetype' }],
}

在我想要渲染的HTML元素中,添加CSS fontFamily 属性就足以设置字体。
<span style={{ fontFamily: 'Balsamiq-Sans', ... }}>Almost before we knew it, we had left the ground </span>

它实际上是有效的,因为它使用正确的balsamiq sans字体来呈现给定文本,但间距看起来不对。
这是在HTML页面中使用balsamiq sans的输入方式 Look in html
但生成的PDF看起来非常不同 PDF output
就像单词之间的空格被缩小了一样,这种情况发生在许多谷歌字体中(但其中一些像Dosis或Oswald一样运行良好)。
我尝试使用Font squirrel工具生成Web字体以消除字距、更改x高度匹配等,并在html方法的fontface对象配置中使用生成的ttf,但没有成功。我还尝试了不同的stretch选项在FontFaces对象中,从'ultra-condensed'到'ultra-expanded'都没有效果。
我想知道是否有办法改变字体间距或其他的东西可以帮助解决这个问题。非常感谢任何关于此问题的建议,我已经搜索了几天但没有发现解决方法。
更新:
我尝试过使用jspdf v2.5.0中的fontFaces API(如这里所示)和addFileToVFS(如这里所示),将字体嵌入PDF中。
const font = '<base64 font content string>';
doc.addFileToVFS('balsamiqsans-regular-webfont-normal.ttf', font);
doc.addFont('balsamiqsans-regular-webfont-normal.ttf', 'Balsamiq-Sans', 'normal');
doc.setFont('Balsamiq-Sans');

无论哪种情况,我都可以使用Linux Bash工具pdffonts在PDF中看到嵌入的字体:

在此输入图像描述

你是否将字体嵌入到PDF中?还是依赖于设备安装的字体? - Ouroborus
我正在使用fontFaces对象将其嵌入到html方法中,参考http://raw.githack.com/MrRio/jsPDF/master/docs/module-html.html#~html - nowxue
你有找到解决这个问题的任何办法吗?我也遇到了完全相同的问题,而且我尝试过的所有方法都不起作用。 - Sebastien F.
1个回答

5

有个答案指出,将letter-spacing: 0.01px;添加到包含内容的HTML div中:

<div id="content" style="font-family: Balsamiq-Sans, serif; letter-spacing: 0.01px;">

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接