Skip to content
the poor coder

How to add custom font in react-pdf/pdf

Poor Man
Published
Reading time
1 min read
On this page

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:
JavaScript

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

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:
JavaScript


  <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:
HTML

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

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:
JavaScript


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

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC