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.
JavaScript
x
17
17
1
from fpdf import FPDF
2
3
# Makes new pdf
4
nbareport = FPDF('P', 'mm', 'Letter')
5
6
# Imports new fonts
7
nbareport.add_font('CMU Serif', '', r'C:UsersgregdPycharmProjectspythonProject2venvLibsite-packagesmatplotlibmpl-datafontsttfcmu.serif-roman.ttf', uni=True)
8
nbareport.add_font('CMU Serif', 'B', r'C:UsersgregdPycharmProjectspythonProject2venvLibsite-packagesmatplotlibmpl-datafontsttfcmunbx.ttf', uni=True)
9
10
# Create instance of FPDF class
11
# Letter size paper, use inches as unit of measure
12
nbareport = FPDF(format='letter', unit='in')
13
14
nbareport.set_font('CMU Serif', '', 10)
15
nbareport.cell('Hello World!')
16
nbareport.output('test.pdf', 'F')
17
Relevant error message:
JavaScript
1
9
1
Traceback (most recent call last):
2
File "C:UsersgregdPycharmProjectspythonProject2NBA DataFPDF tester.py", line 14, in <module>
3
nbareport.set_font('CMU Serif', '', 10)
4
File "C:UsersgregdPycharmProjectspythonProject2venvlibsite-packagesfpdffpdf.py", line 603, in set_font
5
self.error('Undefined font: '+family+' '+style)
6
File "C:UsersgregdPycharmProjectspythonProject2venvlibsite-packagesfpdffpdf.py", line 227, in error
7
raise RuntimeError('FPDF error: '+msg)
8
RuntimeError: FPDF error: Undefined font: cmu serif
9
Proof of fonts in the correct directory
Thank you!
Advertisement
Answer
This line:
JavaScript
1
2
1
nbreport = FPDF(format='letter', unit='in')
2
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.