4

I'm trying to use my custom font for creating a pdf file using @react-pdf/renderer.

Here is my code:

const styles = StyleSheet.create({
  page: {
    alignItems: "center",
  },
  text: {
    fontFamily: "Nunito",
  },
});

const MainPage = () => {
  Font.register({
    family: "Nunito",
    src: "./ttf/Nunito-Regular.ttf",
  });

  return (
    <Document>
      <Page size="A4" style={styles.page}>
        <Text style={styles.text}>Reserve Number: </Text>
      </Page>
    </Document>
  );
};

and i'm getting this error:

index.js:1 Error: Unknown font format
    at Object.push../node_modules/@react-pdf/fontkit/lib/fontkit.browser.es.js.fontkit.create (fontkit.browser.es.js:49)
    at FontSource._callee2$ (font.js:73)
    at tryCatch (runtime.js:63)
    at Generator.invoke [as _invoke] (runtime.js:294)
    at Generator.next (runtime.js:119)
    at asyncGeneratorStep (asyncToGenerator.js:3)
    at _next (asyncToGenerator.js:25)

and i tried every way of addressing the font, but nothing worked.

any help or would be appreciated. thank you.

Hamid
  • 503
  • 6
  • 22

2 Answers2

7

I had this issue as well. I was able to resolve it by importing the font file as a variable then using that as the src value.

import font from "./font.ttf"

Font.register({
  family: "FamilyName",
  format: "truetype",
  src: font 
});


const styles = StyleSheet.create({
  page: {
    fontFamily: "FamilyName",
  },
 });

this worked for me.

Design Freek
  • 183
  • 2
  • 7
2

I had the same issue,fortunately I was using Google fonts and I solved it by using curl on font import url like so:

curl 'https://fonts.googleapis.com/css2?family=Cairo&display=swap'

And copying the ttf url from the response which shows as such

@font-face {
  font-family: 'Cairo';
  font-style: normal;
  font-weight: 400;
  font-display: swap;
  src: url(https://fonts.gstatic.com/s/cairo/v20/SLXVc1nY6HkvangtZmpcWmhzfH5lWWgsQQ.ttf) format('truetype');
}

Desmond
  • 61
  • 4