如何将图像从qrc.py访问到reportlab? 文件 image_fonts.qrc

问题描述

我已将“ image_fonts.qrc”转换为image_fonts_rc.py文件。它有一个名为“ image.png”的图像

如何从qrc.py文件将图像用于Python的reportlab PDF。

文件 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)

我在行上方使用过,但出现错误。请找到以下错误

TypeError:预期的str,字节或os.pathLike对象,而不是QIcon

最小示例:

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,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.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_()

解决方法

没有必要使用QPixmap或QIcon,但必须像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)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...