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
- First, download the font file you want to use and save it somewhere in your project folder.
- Import the font file in your React component like this:
import myFont from './path/to/myFont.ttf';
- 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>
  )
}
- 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:
- First, add the link to the Google Font in your HTML file:
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
- 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>
  )
}
- 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.