打印具有特定扩展名的文件

xralf

我想打印一个文件选择器(或在某种程度上),具有一定的扩展选择了一个文件,这样PyQt或打印机将自动识别的格式(例如pdfms wordexceltxthtmljpg等)

到目前为止,我已经在这里找到如何打印 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>,但这可以更好地控制图像的定位和大小[s]。

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())。


正如评论中已经解释的那样,打印到其他(可能是专有的)格式需要外部模块。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

递归查找具有特定扩展名的文件

如何删除文件夹中所有具有特定扩展名的文件?

从所有子目录复制具有特定扩展名的所有文件

如何将所有具有特定扩展名的文件移动到特定目录?

Gradle-删除具有特定扩展名的文件

使用Chokidar监视具有特定扩展名的文件

用户如何输入具有特定扩展名的文件名?

获取具有特定扩展名的所有文件

Bash脚本检查具有特定扩展名的文件

如何遍历文件夹中的文件以移动具有特定扩展名的每个文件

具有特定扩展名的文件名的文件路径

如何在具有特定扩展名的文件中查找特定文本?

如何删除特定文件夹中具有特定扩展名的所有文件?

如何将扩展名附加到具有特定文件名格式的文件

Powershell删除具有特定文件扩展名的所有文件

显示所有具有特定扩展名的文件的文件名

从多个目录复制具有特定扩展名的文件

循环浏览具有特定扩展名的文件

从具有特定扩展名的文件中删除行

通过regexp删除具有特定扩展名的文件

如何附加到具有特定扩展名的文件

使用线程删除具有特定扩展名的文件,忽略特定日期的文件

Python递归查找具有特定扩展名的文件

查找具有特定扩展名的文件

使用 grep 移动具有特定扩展名的文件

删除具有特定扩展名的文件的脚本问题

删除具有特定扩展名的诊断文件的脚本

GREP:排除具有特定模式的文件名,同时包含特定的文件扩展名

具有特定字符串或特定扩展名的文件名的 for 循环