Import font and create PDF with PDFmake from React js
I recently got an idea of making a billing application with React js and tried using JsPDF package for generating PDF file. But unfortunately, it doesn’t work with Tamil language fonts properly. So I was searching for a better npm package and got it working with PDFmake. Come let’s explore how to import font and create PDF file with PDFmake package.
Prerequisite:
- We may need to install React js and also include PDFmake package in our project to get started,
npx create-react-app <project_name>
npm i pdfmake
- Also you may need to download our required fonts(file with .ttf extension) from Google or where ever we have it available. I have download Tamil language font from here — Tiro font. By clicking on Download family button, you will get the fonts downloaded.
Converting font into base64 file:
- First step will be converting the font into base64 file, so that we can use it in our PDF file.
- Upload your downloaded font file(TiroTamil-Regular.ttf) into the following website — link.
- Once done, you will get the file converted into base64 encoded text.
- Copy that encode text.
Exporting encoded font into our React project:
- Create a file named “TrioTamil-Regular.js”.
- Paste the copied encoded text and export the constant font,
export const font = "<your_encoded_text_should_be_pasted_here>"
Importing the the required font:
- Now, its time to import the required font into our React js project.
- Using below import commands, we will import the pdfmake and fonts to create our PDF file,
//importing pdfmake to generate our PDF file
import pdfMake from "pdfmake/build/pdfmake"//importing the fonts whichever present inside vfs_fonts file
import pdfFonts from "pdfmake/build/vfs_fonts"//importing the encoded font file into our project
import {font} from './TiroTamil-Regular'//Making use of all the fonts defined
pdfMake.vfs = pdfFonts.pdfMake.vfs//Adding our own font into the vfs
window.pdfMake.vfs["TiroTamil-Regular.ttf"] = font
Creating PDF file:
- Inside App.js file of our react project, lets have only one <div> tag.
- Inside <div> tag, create a button which will trigger a function named printPDF as below,
- Now lets write our function printPDF() to generate PDF file,
- Our final App.js file will look like below,
Generating PDF file from our project:
- All set! We now need to start our React project with below command,
npm run start
- Now you will get our react project home screen open with printPDF button in it,
- Click on the printPDF button, you will get the PDF file with the text which you mentioned in the content.
Hurray!! we are done. Want to explore more with PDFmake? You can make use of their playground — click here.
Above mentioned is my way of importing font, there may be more ways too. Comment below if you have come across any other way. Follow me for more content.
Happy coding!