如何在使用 DOMPdf 生成的 PDF 中使用 google 字体?

How can I use google fonts in PDFs generated with DOMPdf?

在我的 pdf 模板中,我使用了以下样式:

 @font-face {
    font-family: 'Open Sans', sans-serif;
    font-style: normal;
    font-weight: normal;
    src: url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;600;700;800&display=swap');
  }
  table thead tr td{
    font-family: 'Open Sans', sans-serif;
  }
  table tbody tr td{
    font-family: 'Open Sans', sans-serif;
  }

这很好用。我在 pdf 中看到了正确的字体。但是当我想将字体更改为 source sans Pro 字体时,它不起作用。字体设置为 Arial 不是为了 source sans pro:

  @font-face {
    font-family: 'Source Sans Pro', sans-serif;
    font-style: normal;
    font-weight: normal;
    src: url('https://fonts.googleapis.com/css2?family=Source+Sans+Pro:ital,wght@0,200;0,300;0,400;0,600;0,700;0,900;1,200;1,300;1,400;1,600;1,700;1,900&display=swap');
  }
  table thead tr td{
    font-family: 'Source Sans Pro', sans-serif;
  }
  table tbody tr td{
    font-family: 'Source Sans Pro', sans-serif;
  }

这可能是什么原因? 另一个问题,所有以粗体加载的内容现在都设置为正常,即使我删除了字体粗细。

其中一个解决方案是将 link 中的 css 包含到本地文件中。然后提供从您的应用加载外部 css 字体文件的正确路径。

$dompdf = new DOMPDF();
$dompdf->setBasePath(realpath(APPLICATION_PATH . '/path/to/googleapis/fonts.css'));
$dompdf->loadHtml($html);
$dompdf->render();

同时检查 css 来自 https://github.com/dompdf/dompdf/wiki/CSSCompatibility

的不同 css 标签的兼容性