我想打印带有特定扩展名的文件选择器(或以某种方式)选择的文件,以便打印机自动PyQt
识别格式(例如,、、、、等)pdf
ms word
excel
txt
html
jpg
到目前为止,我在这里找到了如何打印 TextEdit 的内容,但我想打印各种格式的文件。
是否可以PyQt5
或应该在其他地方搜索?
我想打印带有特定扩展名的文件选择器(或以某种方式)选择的文件,以便打印机自动PyQt
识别格式(例如,、、、、等)pdf
ms word
excel
txt
html
jpg
到目前为止,我在这里找到了如何打印 TextEdit 的内容,但我想打印各种格式的文件。
是否可以PyQt5
或应该在其他地方搜索?
打印纯文本文档不需要viewer,因为该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 中的QWebEnginePage类。看到这个答案。
不要使用QTextDocument.setHtml()
,因为 Qt 对 html 标签的支持有限。
这同样适用于 PDF 文件,不同之处在于必须通过加载文件并且必须通过setUrl()
启用QWebEngineSettings.PluginsEnabled设置page.settings().setAttribute(setting, bool)
以防万一。
阅读有关PDF 文件查看的文档。
打印图像可以通过两种方法完成。
第一个也是更简单的是,创建一个嵌入图像的临时 html 文件并加载到上面的 web 引擎页面(您可以添加缩放/缩放控件)。
或者,您可以使用 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()
)。
正如评论中已经解释的那样,打印到其他(可能是专有的)格式需要外部模块。