我想打印一个带有特定扩展名的文件选择器(或以某种方式)选择的文件,以便PyQt
或打印机自动识别格式(例如pdf
、ms word
、excel
、txt
、html
、jpg
等)。
到目前为止,我已经找到了这里如何打印TextEdit的内容,但我想打印各种格式的文件。
是否可以使用PyQt5
,还是应该在其他地方搜索?
发布于 2020-02-25 23:39:09
打印纯文本文档不需要查看器,因为print_()
函数实际上调用了内部QDocument的print_()
函数:
filePath, filter = QFileDialog.getOpenFileName(self, 'Open file', '', 'Text (*.txt)')
if not filePath:
return
doc = QtGui.QTextDocument()
try:
with open(filePath, 'r') as txtFile:
doc.setPlainText(txtFile.read())
printer = QtPrintSupport.QPrinter(QtPrintSupport.QPrinter.HighResolution)
if not QtPrintSupport.QPrintDialog(printer, self).exec_():
return
doc.print_(printer)
except Exception as e:
print('Error trying to print: {}'.format(e))
在实际打印之前,您可能需要添加一些功能来设置页面大小、文档页边距、字体大小等(只需阅读QTextDocument文档),这将留给您。
从html文件打印几乎是类似的,但是您需要使用来自QtWebEngineWidgets的QtWebEngineWidgets类。见这个答案。
不要使用QTextDocument.setHtml()
,因为Qt对html标记的支持有限。
同样的方法也适用于PDF文件,不同之处在于文件必须通过setUrl()
加载,而QWebEngineSettings.PluginsEnabled设置必须通过page.settings().setAttribute(setting, bool)
启用,以防不是。
阅读有关PDF文件查看的文档。
打印图像可以通过两种方法进行。
第一个也是更简单的方法是创建一个临时html文件,将图像嵌入到上面的for引擎页面中(您可以添加缩放控件)。
或者,您可以使用QPainter直接打印,但是您必须与打印机分辨率和图像大小相关联,因此您可能希望在实际打印图像之前有一个预览对话框,否则它可能太小(或太大)。
虽然比普通的<html><img src=""></html>
更复杂,但这可以更好地控制图像的位置和大小。
class ImagePrintPreview(QtWidgets.QDialog):
def __init__(self, parent, printer, pixmap):
super().__init__(parent)
self.printer = printer
self.pixmap = pixmap
layout = QtWidgets.QGridLayout(self)
self.viewer = QtWidgets.QLabel()
layout.addWidget(self.viewer, 0, 0, 1, 2)
self.resoCombo = QtWidgets.QComboBox()
layout.addWidget(self.resoCombo, 1, 0)
self.zoom = QtWidgets.QSpinBox(minimum=50, maximum=200, suffix='%')
self.zoom.setValue(100)
self.zoom.setAccelerated(True)
layout.addWidget(self.zoom, 1, 1)
self.zoom.valueChanged.connect(self.updatePreview)
self.buttonBox = QtWidgets.QDialogButtonBox(
QtWidgets.QDialogButtonBox.Ok|QtWidgets.QDialogButtonBox.Cancel)
layout.addWidget(self.buttonBox)
self.buttonBox.accepted.connect(self.accept)
self.buttonBox.rejected.connect(self.reject)
default = printer.resolution()
self.resoCombo.addItem(str(default), default)
for dpi in (150, 300, 600, 1200):
if dpi == default:
continue
self.resoCombo.addItem(str(dpi), dpi)
self.resoCombo.currentIndexChanged.connect(self.updatePreview)
self.updatePreview()
def updatePreview(self):
# create a preview to show how the image will be printed
self.printer.setResolution(self.resoCombo.currentData())
paperRect = self.printer.paperRect(self.printer.DevicePixel)
printRect = self.printer.pageRect(self.printer.DevicePixel)
# a temporary pixmap that will use the printer's page size
# note that page/paper are QRectF, they have a QSizeF which has to
# be converted to a QSize
pm = QtGui.QPixmap(paperRect.size().toSize())
# new pixmap have allocated memory for their contents, which usually
# result in some random pixels, just fill it with white
pm.fill(QtCore.Qt.white)
# start a qpainter on the pixmap
qp = QtGui.QPainter(pm)
# scale the pixmap to the wanted zoom value
zoom = self.zoom.value() * .01
scaled = self.pixmap.scaledToWidth(int(self.pixmap.width() * zoom), QtCore.Qt.SmoothTransformation)
# paint the pixmap aligned to the printing margins
qp.drawPixmap(printRect.topLeft(), scaled)
# other possible alternatives:
# Center the image:
# qp.translate(printRect.center())
# delta = QtCore.QPointF(scaled.rect().center())
# qp.drawPixmap(-delta, scaled)
# To also rotate 90° clockwise, add this to the above:
# qp.rotate(90)
# *after* qp.translate() and before qp.drawPixmap()
# when painting to a non QWidget device, you always have to end the
# painter before being able to use it
qp.end()
# scale the temporary pixmap to a fixed width
self.viewer.setPixmap(pm.scaledToWidth(300, QtCore.Qt.SmoothTransformation))
def exec_(self):
if super().exec_():
self.printer.setResolution(self.resoCombo.currentData())
# do the same as above, but paint directly on the printer device
printRect = self.printer.pageRect(self.printer.DevicePixel)
qp = QtGui.QPainter(self.printer)
zoom = self.zoom.value() * .01
scaled = self.pixmap.scaledToWidth(int(self.pixmap.width() * zoom), QtCore.Qt.SmoothTransformation)
qp.drawPixmap(printRect.topLeft(), scaled)
# as above, that's important!
qp.end()
class ImagePrinter(QtWidgets.QWidget):
def __init__(self):
super().__init__()
layout = QtWidgets.QVBoxLayout(self)
selBtn = QtWidgets.QPushButton('Open image')
layout.addWidget(selBtn)
selBtn.clicked.connect(self.selectFile)
def selectFile(self):
filePath, filter = QtWidgets.QFileDialog.getOpenFileName(self, 'Open file', '/tmp', 'Images (*.jpg *.png)')
if not filePath:
return
pixmap = QtGui.QPixmap(filePath)
if pixmap.isNull():
return
printer = QtPrintSupport.QPrinter(QtPrintSupport.QPrinter.HighResolution)
if QtPrintSupport.QPrintDialog(printer, self).exec_():
ImagePrintPreview(self, printer, pixmap).exec_()
请注意,我无法在windows下测试这一点,因此可能需要更改与分辨率相关的内容(可能通过使用printer.supportedResolutions()
)。
正如注释中已经解释的那样,打印到其他(可能是专有的)格式需要外部模块。
https://stackoverflow.com/questions/60346386
复制相似问题