Search code examples
phpdompdfgoogle-fonts

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


In my pdf template I use the following style:

 @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;
  }

This works fine. I see the correct font in my pdf. But when I want to change the font into source sans Pro font, it is not working. The font is set to Arial not to 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;
  }

What could be a reason for this? The other problem, all content that was loaded with bold is now set to normal, even if I remove the font-weight.


Solution

  • one of the solution is to include the css from the link into a local file. Then provide the right path to load the external css font file from your app.

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

    Also check the css compatibility of different css tags from https://github.com/dompdf/dompdf/wiki/CSSCompatibility