How can I access images from qrc.py into reportlab?

188 views Asked by At

I have converted "image_fonts.qrc" into image_fonts_rc.py file. It has one image named as "image.png"

How can I use an image into reportlab PDF in Python from qrc.py file.

File image_fonts.qrc

<RCC>
  <qresource prefix="image_fonts">
    <file>image.png</file>
    <file>logo.png</file>
  </qresource>
</RCC>
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(":/image_fonts/logo.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)

I used above the lines, but I get an error. Please find the below error.

TypeError: expected str, bytes or os.PathLike object, not QIcon

Minimal Example:

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtSql import *
from PyQt5 import uic
import sys
from reportlab.lib.pagesizes import A4
from reportlab.platypus import SimpleDocTemplate, PageTemplate, TableStyle, Paragraph, Image, Spacer, Frame, Paragraph, Flowable
import image_fonts_rc


class UI(QMainWindow):
    def __init__(self):
        super(UI, self).__init__()
        uic.loadUi("test_images.ui", self)
        self.show()

        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(":/image_fonts/logo.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)

        doc = SimpleDocTemplate("images.pdf", pagesize=A4, rightMargin=40, leftMargin=40, topMargin=20, bottomMargin=20, title ="Images")

        width, height = A4
        document = []

        logo = icon
        imgw = imgh = 80
        im = (Image(logo, width=imgw, height=imgh))

        document.append(im)

        doc.build(document)

app = QApplication(sys.argv)
window = UI()
app.exec_()
1

There are 1 answers

1
eyllanesc On BEST ANSWER

It is not necessary to use QPixmap or QIcon but you must get the bytes from the image as in my previous answer:

from io import BytesIO
from PyQt5 import QtCore

from reportlab.lib.pagesizes import A4
from reportlab.platypus import SimpleDocTemplate, Image

import image_fonts_rc


def convert_qrc_to_bytesio(filename):
    file = QtCore.QFile(filename)
    if not file.open(QtCore.QIODevice.ReadOnly):
        raise RuntimeError(file.errorString())
        return
    f = BytesIO(file.readAll().data())
    return f


doc = SimpleDocTemplate(
    "images.pdf",
    pagesize=A4,
    rightMargin=40,
    leftMargin=40,
    topMargin=20,
    bottomMargin=20,
    title="Images",
)

width, height = A4
document = []

logo = convert_qrc_to_bytesio(":/image_fonts/logo.png")
imgw = imgh = 80
im = Image(logo, width=imgw, height=imgh)

document.append(im)

doc.build(document)