How to set any font in reportlab Canvas in python?
Perhabs Tahoma is a TrueType font, and you need to register it first. According to the user guide of ReportLab you need to do this:
from reportlab.pdfbase import pdfmetricsfrom reportlab.pdfbase.ttfonts import TTFontpdfmetrics.registerFont(TTFont('Vera', 'Vera.ttf'))pdfmetrics.registerFont(TTFont('VeraBd', 'VeraBd.ttf'))pdfmetrics.registerFont(TTFont('VeraIt', 'VeraIt.ttf'))pdfmetrics.registerFont(TTFont('VeraBI', 'VeraBI.ttf'))canvas.setFont('Vera', 32)canvas.drawString(10, 150, "Some text encoded in UTF-8")canvas.drawString(10, 100, "In the Vera TT Font!")
The canvas object has a getAvailableFonts
method that should return all currently registered (and therefore usable) fonts.
Start at Reiner's answer.
It is perfect with one caveat.
Reportlab only searches for fonts in predefined folders:
TTFSearchPath = ( 'c:/winnt/fonts', 'c:/windows/fonts', '/usr/lib/X11/fonts/TrueType/', '/usr/share/fonts/truetype', '/usr/share/fonts', #Linux, Fedora '/usr/share/fonts/dejavu', #Linux, Fedora '%(REPORTLAB_DIR)s/fonts', #special '%(REPORTLAB_DIR)s/../fonts', #special '%(REPORTLAB_DIR)s/../../fonts',#special '%(CWD)s/fonts', #special '~/fonts', '~/.fonts', '%(XDG_DATA_HOME)s/fonts', '~/.local/share/fonts', #mac os X - from #http://developer.apple.com/technotes/tn/tn2024.html '~/Library/Fonts', '/Library/Fonts', '/Network/Library/Fonts', '/System/Library/Fonts', )
If you're trying to use a ttf font that you've downloaded off of the internet, and would like that font available on all your servers, I would suggest the following:
- Add the font to your project in any directory. e.g.: /project_root/app/lib/reportlabs/fonts/
Make sure you have something like BASE_DIR/ROOT_DIR in your settings:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
add the following line to a python file that generates pdf:
import reportlabfrom django.conf import settingsreportlab.rl_config.TTFSearchPath.append(str(settings.BASE_DIR) + '/app/lib/reportlabs/fonts')pdfmetrics.registerFont(TTFont('Copperplate', 'Copperplate-Gothic-Bold.ttf'))