Search code examples
reactjsreact-pdf

How to use Custom font for @react-pdf/renderer


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.


Solution

  • 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.