问题描述
我已将“ 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)