How to access image and fonts from qrc.py into reportlab?

386 views Asked by At

I am using

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

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

<RCC>
  <qresource prefix="image_fonts">
    <file>Arial-Bold.TTF</file>
    <file>logo.png</file>
    <file>Arial.TTF</file>
  </qresource>
</RCC>
1

There are 1 answers

4
eyllanesc On BEST ANSWER

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()