1

我在用

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>
4

1 回答 1

2

一种可能的解决方案是使用 QFile 读取字体并将其保存在 io.BytesIO 已经可以被 TTFont reportlab 读取:

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()
于 2020-10-20T16:02:59.847 回答