Greg Gassen
Greg Gassen

Reputation: 5

Problem importing fonts with FPDF using python

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:\Windows\Fonts directory.

from fpdf import FPDF

# Makes new pdf
nbareport = FPDF('P', 'mm', 'Letter')

# Imports new fonts
nbareport.add_font('CMU Serif', '', r'C:\Users\gregd\PycharmProjects\pythonProject2\venv\Lib\site-packages\matplotlib\mpl-data\fonts\ttf\cmu.serif-roman.ttf', uni=True)
nbareport.add_font('CMU Serif', 'B', r'C:\Users\gregd\PycharmProjects\pythonProject2\venv\Lib\site-packages\matplotlib\mpl-data\fonts\ttf\cmunbx.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:\Users\gregd\PycharmProjects\pythonProject2\NBA Data\FPDF tester.py", line 14, in <module>
    nbareport.set_font('CMU Serif', '', 10)
  File "C:\Users\gregd\PycharmProjects\pythonProject2\venv\lib\site-packages\fpdf\fpdf.py", line 603, in set_font
    self.error('Undefined font: '+family+' '+style)
  File "C:\Users\gregd\PycharmProjects\pythonProject2\venv\lib\site-packages\fpdf\fpdf.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!

Upvotes: 0

Views: 2848

Answers (1)

Tim Roberts
Tim Roberts

Reputation: 54698

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.

Upvotes: 2

Related Questions