簡體   English   中英

如何在python的reportlab畫布中設置任何字體?

[英]How to set any font in reportlab Canvas in python?

我正在使用reportlab創建pdf。 當我嘗試使用以下方法設置字體時,出現KeyError

pdf = Canvas('test.pdf')
pdf.setFont('Tahoma', 16)

但是,如果我使用'Courier'而不是'Tahoma'那沒有問題。 如何使用Tahoma?

Perhabs Tahoma是TrueType字體,您需要首先注冊它。 根據ReportLab的用戶指南,您需要執行以下操作:

from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont

pdfmetrics.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!")

canvas對象具有getAvailableFonts方法,該方法應返回所有當前已注冊(因此可用)的字體。

Reiner的答案開始。

一個警告是完美的。

Reportlab僅在預定義的文件夾中搜索字體:

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',
            )

如果您嘗試使用從Internet上下載的ttf字體,並且希望該字體在所有服務器上都可用,則建議您執行以下操作:

  • 將字體添加到項目的任何目錄中。 例如:/ project_root / app / lib / reportlabs / fonts /
  • 確保您的設置中包含BASE_DIR / ROOT_DIR之類的內容:

     BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 
  • 將以下行添加到生成pdf的python文件中:

     import reportlab from django.conf import settings reportlab.rl_config.TTFSearchPath.append(str(settings.BASE_DIR) + '/app/lib/reportlabs/fonts') pdfmetrics.registerFont(TTFont('Copperplate', 'Copperplate-Gothic-Bold.ttf')) 

通過將DejaVuSans Font添加到應用程序中,解決了我的問題。 這是代碼片段

pdfmetrics.registerFont(TTFont('DejaVuSans','DejaVuSans.ttf'))

並使用UTF8進行所有編碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM