pdfmake - cant find the font files on vfs

user1247395 picture user1247395 · Feb 16, 2018 · Viewed 8.5k times · Source

I have the following code I am using to test drive PDFmake. I am having an issue with the location of the font files. I see documentation that seem to indicate that after pulling in the vfs_fonts file that I should be able to see them. However this is not the case for me.

function createPdf(assessmentId: string): string {
  const pdfMake = require('pdfmake/build/pdfmake.js');
  const pdfFonts = require('pdfmake/build/vfs_fonts.js');
  pdfMake.vfs = pdfFonts.pdfMake.vfs;

  //required font setup, requires that you link to the fonts shipped with npm

  const fontDescriptors = {
    Roboto: {
      normal: 'Roboto-Regular.ttf',
      bold: 'Roboto-Medium.ttf',
      italics: 'Roboto-Italic.ttf',
      bolditalics: 'Roboto-Italic.ttf',
    }
  };
  const termpaper = new PdfLayout();
  const docDefinition = termpaper.layout
  const printer = new Printer(fontDescriptors);

  //get a reference to the PdfKit instance, which is a streaming interface

  const pdfDoc = printer.createPdfKitDocument(docDefinition);

  return "pdflocation";
}

When this code executes I get this error.

Error:

ENOENT: no such file or directory, open 'Roboto-Medium.ttf' at Error (native) at Object.fs.openSync (fs.js:642:18) at Object.fs.readFileSync (fs.js:510:33) at Object.fontkit.openSync (/user_code/node_modules/pdfmake/node_modules/fontkit/index.js:43:19) at Function.PDFFont.open (/user_code/node_modules/pdfmake/node_modules/pdfkit/js/font.js:14:24) at PDFDocument.font (/user_code/node_modules/pdfmake/node_modules/pdfkit/js/mixins/fonts.js:39:28) at FontProvider.provideFont (/user_code/node_modules/pdfmake/src/fontProvider.js:49:58) at /user_code/node_modules/pdfmake/src/textTools.js:258:27 at Array.forEach (native) at measure (/user_code/node_modules/pdfmake/src/textTools.js:240:13)

What do I need to do to properly find these font files?

Answer

rozza2058 picture rozza2058 · Feb 26, 2018

I struggled with this too. The solution I found was to actually include the font files in my project. The files listed are in the 'fonts' folder at the root of my project, and my code references them by uri:

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

I downloaded the font files from here.

Hope this helps.