I’ve been trying to import specialty fonts beyond what is default included with the FPDF package with Python, using the pdf.add_font()
command. The code below produces an error of an Undefined font, as though I didn’t just use pdf.add_font()
. Below you can find a sample of my code, as well as proof that the relevant fonts are in the directory specified in the pdf.add_font()
command. I have also tried installing the relevant fonts in the C:WindowsFonts
directory.
from fpdf import FPDF # Makes new pdf nbareport = FPDF('P', 'mm', 'Letter') # Imports new fonts nbareport.add_font('CMU Serif', '', r'C:UsersgregdPycharmProjectspythonProject2venvLibsite-packagesmatplotlibmpl-datafontsttfcmu.serif-roman.ttf', uni=True) nbareport.add_font('CMU Serif', 'B', r'C:UsersgregdPycharmProjectspythonProject2venvLibsite-packagesmatplotlibmpl-datafontsttfcmunbx.ttf', uni=True) # Create instance of FPDF class # Letter size paper, use inches as unit of measure nbareport = FPDF(format='letter', unit='in') nbareport.set_font('CMU Serif', '', 10) nbareport.cell('Hello World!') nbareport.output('test.pdf', 'F')
Relevant error message:
Traceback (most recent call last): File "C:UsersgregdPycharmProjectspythonProject2NBA DataFPDF tester.py", line 14, in <module> nbareport.set_font('CMU Serif', '', 10) File "C:UsersgregdPycharmProjectspythonProject2venvlibsite-packagesfpdffpdf.py", line 603, in set_font self.error('Undefined font: '+family+' '+style) File "C:UsersgregdPycharmProjectspythonProject2venvlibsite-packagesfpdffpdf.py", line 227, in error raise RuntimeError('FPDF error: '+msg) RuntimeError: FPDF error: Undefined font: cmu serif
Proof of fonts in the correct directory
Thank you!
Advertisement
Answer
This line:
nbreport = FPDF(format='letter', unit='in')
creates a brand-new FPDF instance and helpfully deletes the one in which you so carefully added the fonts. You need to add the fonts to the instance you’re actually using.