Skip to content

Custom Fonts client side

Libor M edited this page May 3, 2017 · 15 revisions

vfs_fonts.js assigns a "virtual-file-system" object to pdfMake.vfs

Each key of this object is a filename, while value contains base64 encoded file content.

When you run

gulp buildFonts

a new vfs_fonts.js is created, containing all files from examples/fonts directory.

To use custom fonts, 3 steps are required:

  1. create vfs_fonts.js containing your fonts
  2. define font family
  3. change font family in doc-definition-object

1. create vfs_fonts.js containing your fonts

Copy your fonts to examples/fonts directory

run gulp buildFonts (you can update gulpfile.js if you'd like to change base directory or add an alternative config for buildFonts task)

Use your new build/vfs_fonts.js on your web page

BTW - the above action dumps all files from examples/fonts (not only fonts), which means you could put images there, run gulp buildFonts and reference them by name in doc-definition-object

2. define font family

before calling pdfMake.createPdf(docDefinition) set pdfMake.fonts to the following object:

{
   yourFontName: {
     normal: 'fontFile.ttf',
     bold: 'fontFile2.ttf',
     italics: 'fontFile3.ttf',
     bolditalics: 'fontFile4.ttf'
   },
   anotherFontName: {
     (...)
   },

   // example of usage fonts in colleciton
   PingFangSC: {
     normal: ['fonts/pingfang.ttc', 'PingFangSC-Regular'],
     bold: ['fonts/pingfang.ttc', 'PingFangSC-Semibold'],
   }
}

keys are font-family names you can later use in doc-definition

Each font-family defines 4 properties: normal, bold, italics and bolditalics referring to appropriate files (by default these are file paths relative to examples/fonts/)

By default pdfMake uses the following structure:

{
        Roboto: {
                normal: 'Roboto-Regular.ttf',
                bold: 'Roboto-Medium.ttf',
                italics: 'Roboto-Italic.ttf',
                bolditalics: 'Roboto-MediumItalic.ttf'
        }
};

3. change font family in doc-definition-object

Currently pdfmake uses 'Roboto' as default family name, so in order to use your font, you should change it. The easiest way is to do it globally in defaultStyle

var docDefinition = {
  content: (...),
  defaultStyle: {
    font: 'yourFontName'
  }
}

I know this it is overly complicated at the moment.

I'm going to change it in 0.2.0

Source: Use custom font

Clone this wiki locally