How to add custom font in react-pdf/pdf

Adding Custom Font in React-PDF/PDF

As a developer, I had to create a PDF file using React-PDF/PDF library and I wanted to use a custom font for the text in my PDF. Here is how I added the custom font:

Using Font File

  1. First, download the font file you want to use and save it somewhere in your project folder.
  2. Import the font file in your React component like this:

import myFont from './path/to/myFont.ttf';
  1. Then, define the font family like this:

const styles = StyleSheet.create({
  customFont: {
    fontFamily: 'MyCustomFont',
  },
});

const MyComponent = () => {
  return (
    <Document>
      <Page>
        <Text style={styles.customFont}>Hello World!</Text>
      </Page>
    </Document>
  )
}
  1. Finally, import the font into the PDF document:


  <Font src={myFont} family="MyCustomFont" />
  <Page>
    <Text style={styles.customFont}>Hello World!</Text>
  </Page>

Using Google Fonts

If you prefer using Google Fonts, here is how to do it:

  1. First, add the link to the Google Font in your HTML file:

<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
  1. Then, define the font family in your React component:

const styles = StyleSheet.create({
  customFont: {
    fontFamily: 'Roboto',
  },
});

const MyComponent = () => {
  return (
    <Document>
      <Page>
        <Text style={styles.customFont}>Hello World!</Text>
      </Page>
    </Document>
  )
}
  1. Finally, use the font in your PDF document:


  <Font file="https://fonts.gstatic.com/s/roboto/v18/KFOmCnqEu92Fr1Mu4mxK.woff2" family="Roboto" />
  <Page>
    <Text style={styles.customFont}>Hello World!</Text>
  </Page>

That's it! I hope this helps you add custom fonts to your PDF using React-PDF/PDF library.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe