问题描述
我正在使用
pdfmetrics.registerFont(TTFont('Arial','Arial.ttf'))
pdfmetrics.registerFont(TTFont('Arial-Bold','Arial-Bold.ttf'))
我已经转换了"image_fonts.qrc" into image_fonts_rc.py file
。它有一个名为"image.png" and "Arial-Bold.ttf"
的图像
我的问题是如何从qrc.py文件将图像和字体用于python的reportlab PDF。
image_fonts.qrc
<RCC>
<qresource prefix="image_fonts">
<file>Arial-Bold.TTF</file>
<file>logo.png</file>
<file>Arial.TTF</file>
</qresource>
</RCC>
解决方法
一种可能的解决方案是使用QFile读取字体并将其保存在io中。TTFontreportlab已经可以读取字节IO:
from io import BytesIO
from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from PyQt5.QtCore import QFile,QIODevice
import image_fonts_rc
def convert_qrc_to_bytesio(filename):
file = QFile(filename)
if not file.open(QIODevice.ReadOnly):
raise RuntimeError(file.errorString())
return
f = BytesIO(file.readAll().data())
return f
pdfmetrics.registerFont(
TTFont("Arial",convert_qrc_to_bytesio(":/image_fonts/Arial.TTF"))
)
pdfmetrics.registerFont(
TTFont("Arial-Bold",convert_qrc_to_bytesio(":/image_fonts/Arial-Bold.TTF"))
)
c = canvas.Canvas("hello.pdf")
c.setFont("Arial",32)
c.drawString(100,750,"Welcome to Reportlab!")
c.save()