Custom Fonts not loaded when pdf generated

See original GitHub issue

I try to generate a PDF with custom font but it doesn’t work when I inject fonts like this :

import { injectGlobal } from 'styled-components'
import Book from './assets/fonts/718/sevenoneeight-medium.woff2';
import Book2 from './assets/fonts/718/sevenoneeight-medium.woff';

injectGlobal `
@font-face {
	font-family: "718book";
	src: url(${Book}) format("woff2"),
		url(${Book2}) format("woff");
}

body {
  font-family: '718book';
  -webkit-print-color-adjust: exact;
}
`;

Someone have an idea how to import fonts correclty ? I need a solution that works with any url -> http://localhost:3000, http://xxxxx.com

It works when I generated a fonts folder in my build and I inject fonts like this :


injectGlobal `
@font-face {
	font-family: "718book";
	src: url('http://localhost:3000/fonts/718/sevenoneeight-medium.woff2') format("woff2"),
		url('http://localhost:3000/fonts/718/sevenoneeight-medium.woff') format("woff");
}
`;

I convert my html to pdf like this :

let convertHTMLToPDF = async (html, callback, options = null) => {
    if (typeof html !== 'string') {
        throw new Error('xxxx.');
    }
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.setRequestInterception(true);

    page.once('request', request => {
        request.respond({ body: html });
        page.on('request', request => request.continue());
    });

    const response = await page.goto('https://google.com');
    await page.setContent((await response.buffer()).toString('utf8'));
    await page.evaluateHandle('document.fonts.ready');
    await page.pdf(options).then(callback, function(error) {
        console.log(error);
    });
    await browser.close();
};

Issue Analytics

  • State:open
  • Created 5 years ago
  • Reactions:37
  • Comments:19

github_iconTop GitHub Comments

16reactions
616b2fcommented, Dec 7, 2022

@elrumordelaluz @billyvg What worked for us is to wait till the font’s are actually loaded before you create your pdf file, using this command:

await page.evaluateHandle('document.fonts.ready');

This seems the best solution so far. As you can use custom fonts that are registered system wide and do not need to load them as base64 strings.

All credits go to this post: https://github.com/puppeteer/puppeteer/issues/422#issuecomment-708142856

EDIT: Important to note that we are using custom fonts that are imported system wide and NOT inline as base64 encoded.

7reactions
elrumordelaluzcommented, May 29, 2020

I’ll expose my tests in case is useful for anyone to continue debug or to find a better solution:

I am generating a pdf from an html string. Something like:

await page.goto(`data:text/html,${htmlString)}`, { waitUntil: 'networkidle0' })
const pdf = await page.pdf()

Since the html string uses an external font I tried different options that I’ll describe below. However only the last one works without differences on two environments. I am testing in local using OSX and in an external server using Linux. Here are the different options I tried:

  • Adding @import url('https://fonts.googleapis.com/css2?family=…'); into a <style> tag of the html string passed
  • Passing that url as addStyleTag url
  • Serving the web fonts and stylesheet in the same server where puppeteer is working and passing a addStyleTag path
  • Also tried playing with await page.evaluateHandle('document.fonts.ready') and another waitUntil values.

In all those scenarios, the resulting pdf were generated with the wrong font and using different fallback, since are different operating systems.

The solution that works cross platform is to pass this css declaration inside the html string:

@font-face {
      font-family: 'Inconsolata';
      src: url(data:application/font-woff2;charset=utf-8;base64,…),
         url(data:application/font-woff;charset=utf-8;base64,…);
      font-weight: normal;
      font-style: normal;
}

I hope there are better solutions since the base64 string for only one style of a font family is pretty big, and increases in cases where more styles or families are needed in the same page.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Custom fonts not working in Generated PDF using ...
I am trying to include some custom google fonts for my PDF file, but those fonts are not working in generated PDF file....
Read more >
Custom font style is not applied in the generated pdf document
1. First check the Font Embeddability of the custom font that you want to use is set to Editable or Installable. · 2....
Read more >
custom fonts not loading in pdf but do appear in screenshots.
I have a website and trying create printPDF files dynamically using the puppeteer lib but the pdf that is generated does not include...
Read more >
How to Load Custom Fonts in a PDF - CraftMyPDF.com
(i) If you are using a font on cdnfonts.com, please make sure to change the protocol to https:// and use @import to load...
Read more >
Custom font usage results in 135 Adobe error and PDF not ...
Is the font loaded using CSS @font declarations or did you install it into dompdf? If the latter and you copied your local...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found