本文介绍了如何从 qrc.py 访问图像和字体到 reportlab?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用

pdfmetrics.registerFont(TTFont('Arial', 'Arial.ttf'))
pdfmetrics.registerFont(TTFont('Arial-Bold', 'Arial-Bold.ttf'))

我已经转换了 image_fonts.qrc"进入 image_fonts_rc.py 文件.它有一个名为 "image.png" 的图像.和Arial-Bold.ttf"我的问题是如何在 python 中从 qrc.py 文件中将图像和字体使用到 reportlab PDF 中.

I have converted "image_fonts.qrc" into image_fonts_rc.py file. It has one image named as "image.png" and "Arial-Bold.ttf"My question is How to use image and fonts into reportlab PDF in python from qrc.py file.

image_fonts.qrc

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.BytesIO 已经可以被 TTFont reportlab 读取:

A possible solution is to read the font using QFile and save it in io.BytesIO can already be read by 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()

这篇关于如何从 qrc.py 访问图像和字体到 reportlab?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 21:03