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

now*_*xue 3 javascript fonts jspdf

我正在使用 .html 方法将 html 转换为 pdf,如下所示:

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

fontFaces 被定义为一个数组或像这样的对象(使用谷歌字体):

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

在我想要渲染的html元素中,添加一个css fontFamily属性就足以设置字体

<span style={{ fontFamily: 'Balsamiq-Sans', ... }}>Almost before we knew it, we had left the ground </span>
Run Code Online (Sandbox Code Playgroud)

它实际上有效,因为它使用正确的 balsamiq sans 字体来呈现给定的文本,但间距看起来错误。

这是 balsamiq sans 的 HTML 页面中输入的样子在 html 中查看

但生成的 PDF 看起来非常不同PDF输出

就像单词之间的间距减少了一样,谷歌字体中的很多字体都会发生这种情况(但其中一些字体工作得很好,比如 Dosis 或 Oswald)。

我尝试过使用Font squirrel 工具生成 Web 字体以删除字距调整、更改 x 高度匹配等,并在 html 方法的 fontface 对象配置中使用生成的 ttf,但没有任何运气。我还尝试了 FontFaces 对象中不同的拉伸选项,从“超压缩”到“超扩展”,但没有效果。

我想知道是否有办法改变字体的间距或有帮助的东西。我很感谢对此的任何建议,我已经搜索了几天但没有运气。

更新:

我尝试使用 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');
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,我都使用 Linux bash 工具 pdffonts 在 PDF 中看到嵌入字体: 在此输入图像描述

Ale*_*sev 6

一个答案,将内容添加letter-spacing: 0.01px;到您的 HTMLdiv中:

<div id="content" style="font-family: Balsamiq-Sans, serif; letter-spacing: 0.01px;">
Run Code Online (Sandbox Code Playgroud)