Search code examples
javascriptpdf-generation

pdfMake: Use System Fonts


I am using the pdfMake-library to generate PDF documents on the client side in one of my applications. My main problem when using the library is that it relies on having available fonts in a virtual file system. The fonts are therefore sent to the client in a JavaScript file called vfs_fonts.js and are then loaded into the virtual file system and later embedded in the resulting PDF-file (of course only the used character subset of the whole font).

With the default settings the library uses the Roboto font and therefore sends a little more than 800kb only for the fonts. My main intuition here is:

Why doesn't it use the system fonts and as a result saves traffic?

Is there a workaround to make it use system fonts?

My current approach to reduce the traffic is to remove the font styles from the vfs_fonts.js that aren't used in the documents that I create. E.g. I remove the italic, bold style and italic/bold style when only using regular styles. With this method I was at least able to reduce the size of the font file by 3/4.


Solution

  • I am also using PDFmake and I have encountered a similar problem.

    You have to add any new source through a corresponding key, like this:

    pdfmake.fonts = {
       'Roboto' : {
          normal: 'Roboto-Regular.ttf',
          bold: 'Roboto-Medium.ttf',
          italics: 'Roboto-Italic.ttf',
          bolditalics: 'Roboto-Italic.ttf'
       },
    
       'OpenSans' : {
          normal: 'OpenSans-Regular.ttf',
          bold: 'OpenSans-Medium.ttf',
          italics: 'OpenSans-Italic.ttf',
          bolditalics: 'OpenSans-Italic.ttf'
       }
    
    }
    

    Then in the PDF content you must add the "font" that you are going to use.

    {
       stack : [
          { 
             text : 'this is a test text',
             font  : 'OpenSans',
             italic : true
          }, { 
             text : 'this is another test text',
             font : 'Roboto',
             bold : true
          }  
       ]
    }
    

    I hope you find it a good solution for people who are looking for a solution.

    Source here. Thanks to Daniel Arbiol (Darbiol).