python3+PyQt5实现文档打印功能
这篇文章主要为大家详细介绍了python3+PyQt5实现文档打印功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文通过Python3+PyQt5实现《python Qt Gui 快速编程》这本书13章文档打印功能。本文共通过三种方式:
1、使用HTML和QTextDOcument打印文档
2、使用QTextCusor和QTextDocument打印文档
3、使用QPainter打印文档
使用Qpainter打印文档比QTextDocument需要更操心和复杂的计算,但是QPainter确实能够对输出赋予完全控制。
#!/usr/bin/env python3 import math import sys import html from PyQt5.QtPrintSupport import QPrinter,QPrintDialog from PyQt5.QtCore import (QDate, QRectF, Qt) from PyQt5.QtWidgets import (QApplication,QDialog, QHBoxLayout,QPushButton, QTableWidget, QTableWidgetItem,QVBoxLayout) from PyQt5.QtGui import (QFont,QFontMetrics,QPainter,QTextCharFormat, QTextCursor, QTextDocument, QTextFormat, QTextOption, QTextTableFormat, QPixmap,QTextBlockFormat) import qrc_resources from PyQt5.QtPrintSupport import QPrinter,QPrintDialog from PyQt5.QtCore import (QDate, QRectF, Qt) from PyQt5.QtWidgets import (QApplication,QDialog, QHBoxLayout,QPushButton, QTableWidget, QTableWidgetItem,QVBoxLayout) from PyQt5.QtGui import (QFont,QFontMetrics,QPainter,QTextCharFormat, QTextCursor, QTextDocument, QTextFormat, QTextOption, QTextTableFormat, QPixmap,QTextBlockFormat) import qrc_resources DATE_FORMAT = "MMM d, yyyy" class Statement(object): def __init__(self, company, contact, address): self.company = company self.contact = contact self.address = address self.transactions = [] # List of (QDate, float) two-tuples def balance(self): return sum([amount for date, amount in self.transactions]) class Form(QDialog): def __init__(self, parent=None): super(Form, self).__init__(parent) self.printer = QPrinter() self.printer.setPageSize(QPrinter.Letter) self.generateFakeStatements() self.table = QTableWidget() self.populateTable() cursorButton = QPushButton("Print via Q&Cursor") htmlButton = QPushButton("Print via &HTML") painterButton = QPushButton("Print via Q&Painter") quitButton = QPushButton("&Quit") buttonLayout = QHBoxLayout() buttonLayout.addWidget(cursorButton) buttonLayout.addWidget(htmlButton) buttonLayout.addWidget(painterButton) buttonLayout.addStretch() buttonLayout.addWidget(quitButton) layout = QVBoxLayout() layout.addWidget(self.table) layout.addLayout(buttonLayout) self.setLayout(layout) cursorButton.clicked.connect(self.printViaQCursor) htmlButton.clicked.connect(self.printViaHtml) painterButton.clicked.connect(self.printViaQPainter) quitButton.clicked.connect(self.accept) self.setWindowTitle("Printing") def generateFakeStatements(self): self.statements = [] statement = Statement("Consality", "Ms S. Royal", "234 Rue Saint Hyacinthe, 750201, Paris") statement.transactions.append((QDate(2007, 8, 11), 2342)) statement.transactions.append((QDate(2007, 9, 10), 2342)) statement.transactions.append((QDate(2007, 10, 9), 2352)) statement.transactions.append((QDate(2007, 10, 17), -1500)) statement.transactions.append((QDate(2007, 11, 12), 2352)) statement.transactions.append((QDate(2007, 12, 10), 2352)) statement.transactions.append((QDate(2007, 12, 20), -7500)) statement.transactions.append((QDate(2007, 12, 20), 250)) statement.transactions.append((QDate(2008, 1, 10), 2362)) self.statements.append(statement) statement = Statement("Demamitur Plc", "Mr G. Brown", "14 Tall Towers, Tower Hamlets, London, WC1 3BX") statement.transactions.append((QDate(2007, 5, 21), 871)) statement.transactions.append((QDate(2007, 6, 20), 542)) statement.transactions.append((QDate(2007, 7, 20), 1123)) statement.transactions.append((QDate(2007, 7, 20), -1928)) statement.transactions.append((QDate(2007, 8, 13), -214)) statement.transactions.append((QDate(2007, 9, 15), -3924)) statement.transactions.append((QDate(2007, 9, 15), 2712)) statement.transactions.append((QDate(2007, 9, 15), -273)) #statement.transactions.append((QDate(2007, 11, 8), -728)) #statement.transactions.append((QDate(2008, 2, 7), 228)) #statement.transactions.append((QDate(2008, 3, 13), -508)) #statement.transactions.append((QDate(2008, 3, 22), -2481)) #statement.transactions.append((QDate(2008, 4, 5), 195)) self.statements.append(statement) def populateTable(self): headers = ["Company", "Contact", "Address", "Balance"] self.table.setColumnCount(len(headers)) self.table.setHorizontalHeaderLabels(headers) self.table.setRowCount(len(self.statements)) for row, statement in enumerate(self.statements): self.table.setItem(row, 0, QTableWidgetItem(statement.company)) self.table.setItem(row, 1, QTableWidgetItem(statement.contact)) self.table.setItem(row, 2, QTableWidgetItem(statement.address)) item = QTableWidgetItem("$ {0:,.2f}".format(float(statement.balance()))) item.setTextAlignment(Qt.AlignRight|Qt.AlignVCenter) self.table.setItem(row, 3, item) self.table.resizeColumnsToContents() def printViaHtml(self): htmltext = "" for statement in self.statements: date = QDate.currentDate().toString(DATE_FORMAT) address = html.escape(statement.address).replace( ",", "<br>") contact = html.escape(statement.contact) balance = statement.balance() htmltext += ("<p align=right><img src=':/logo.png'></p>" "<p align=right>Greasy Hands Ltd." "<br>New Lombard Street" "<br>London<br>WC13 4PX<br>{0}</p>" "<p>{1}</p><p>Dear {2},</p>" "<p>The balance of your account is $ {3:,.2f}.").format( date, address, contact, float(balance)) if balance < 0: htmltext += (" <p><font color=red><b>Please remit the " "amount owing immediately.</b></font>") else: htmltext += (" We are delighted to have done business " "with you.") htmltext += ("</p><p> </p><p>" "<table border=1 cellpadding=2 " "cellspacing=2><tr><td colspan=3>" "Transactions</td></tr>") for date, amount in statement.transactions: color, status = "black", "Credit" if amount < 0: color, status = "red", "Debit" htmltext += ("<tr><td align=right>{0}</td>" "<td>{1}</td><td align=right>" "<font color={2}>$ {3:,.2f}</font></td></tr>".format( date.toString(DATE_FORMAT), status, color,float(abs(amount)))) htmltext += ("</table></p><p style='page-break-after:always;'>" "We hope to continue doing " "business with you,<br>Yours sincerely," "<br><br>K. Longrey, Manager</p>") dialog = QPrintDialog(self.printer, self) if dialog.exec_(): document = QTextDocument() document.setHtml(htmltext) document.print_(self.printer) def printViaQCursor(self): dialog = QPrintDialog(self.printer, self) if not dialog.exec_(): return logo = QPixmap(":/logo.png") headFormat = QTextBlockFormat() headFormat.setAlignment(Qt.AlignLeft) headFormat.setTextIndent( self.printer.pageRect().width() - logo.width() - 216) bodyFormat = QTextBlockFormat() bodyFormat.setAlignment(Qt.AlignJustify) lastParaBodyFormat = QTextBlockFormat(bodyFormat) lastParaBodyFormat.setPageBreakPolicy( QTextFormat.PageBreak_AlwaysAfter) rightBodyFormat = QTextBlockFormat() rightBodyFormat.setAlignment(Qt.AlignRight) headCharFormat = QTextCharFormat() headCharFormat.setFont(QFont("Helvetica", 10)) bodyCharFormat = QTextCharFormat() bodyCharFormat.setFont(QFont("Times", 11)) redBodyCharFormat = QTextCharFormat(bodyCharFormat) redBodyCharFormat.setForeground(Qt.red) tableFormat = QTextTableFormat() tableFormat.setBorder(1) tableFormat.setCellPadding(2) document = QTextDocument() cursor = QTextCursor(document) mainFrame = cursor.currentFrame() page = 1 for statement in self.statements: cursor.insertBlock(headFormat, headCharFormat) cursor.insertImage(":/logo.png") for text in ("Greasy Hands Ltd.", "New Lombard Street", "London", "WC13 4PX", QDate.currentDate().toString(DATE_FORMAT)): cursor.insertBlock(headFormat, headCharFormat) cursor.insertText(text) for line in statement.address.split(", "): cursor.insertBlock(bodyFormat, bodyCharFormat) cursor.insertText(line) cursor.insertBlock(bodyFormat) cursor.insertBlock(bodyFormat, bodyCharFormat) cursor.insertText("Dear {0},".format(statement.contact)) cursor.insertBlock(bodyFormat) cursor.insertBlock(bodyFormat, bodyCharFormat) balance = statement.balance() cursor.insertText("The balance of your account is $ {0:,.2f}.".format(float(balance))) if balance < 0: cursor.insertBlock(bodyFormat, redBodyCharFormat) cursor.insertText("Please remit the amount owing " "immediately.") else: cursor.insertBlock(bodyFormat, bodyCharFormat) cursor.insertText("We are delighted to have done " "business with you.") cursor.insertBlock(bodyFormat, bodyCharFormat) cursor.insertText("Transactions:") table = cursor.insertTable(len(statement.transactions), 3, tableFormat) row = 0 for date, amount in statement.transactions: cellCursor = table.cellAt(row, 0).firstCursorPosition() cellCursor.setBlockFormat(rightBodyFormat) cellCursor.insertText(date.toString(DATE_FORMAT), bodyCharFormat) cellCursor = table.cellAt(row, 1).firstCursorPosition() if amount > 0: cellCursor.insertText("Credit", bodyCharFormat) else: cellCursor.insertText("Debit", bodyCharFormat) cellCursor = table.cellAt(row, 2).firstCursorPosition() cellCursor.setBlockFormat(rightBodyFormat) format = bodyCharFormat if amount < 0: format = redBodyCharFormat cellCursor.insertText("$ {0:,.2f}".format(float(amount)), format) row += 1 cursor.setPosition(mainFrame.lastPosition()) cursor.insertBlock(bodyFormat, bodyCharFormat) cursor.insertText("We hope to continue doing business " "with you,") cursor.insertBlock(bodyFormat, bodyCharFormat) cursor.insertText("Yours sincerely") cursor.insertBlock(bodyFormat) if page == len(self.statements): cursor.insertBlock(bodyFormat, bodyCharFormat) else: cursor.insertBlock(lastParaBodyFormat, bodyCharFormat) cursor.insertText("K. Longrey, Manager") page += 1 document.print_(self.printer) def printViaQPainter(self): dialog = QPrintDialog(self.printer, self) if not dialog.exec_(): return LeftMargin = 72 sansFont = QFont("Helvetica", 10) sansLineHeight = QFontMetrics(sansFont).height() serifFont = QFont("Times", 11) fm = QFontMetrics(serifFont) DateWidth = fm.width(" September 99, 2999 ") CreditWidth = fm.width(" Credit ") AmountWidth = fm.width(" W999999.99 ") serifLineHeight = fm.height() logo = QPixmap(":/logo.png") painter = QPainter(self.printer) pageRect = self.printer.pageRect() page = 1 for statement in self.statements: painter.save() y = 0 x = pageRect.width() - logo.width() - LeftMargin painter.drawPixmap(x, 0, logo) y += logo.height() + sansLineHeight painter.setFont(sansFont) painter.drawText(x, y, "Greasy Hands Ltd.") y += sansLineHeight painter.drawText(x, y, "New Lombard Street") y += sansLineHeight painter.drawText(x, y, "London") y += sansLineHeight painter.drawText(x, y, "WC13 4PX") y += sansLineHeight painter.drawText(x, y, QDate.currentDate().toString(DATE_FORMAT)) y += sansLineHeight painter.setFont(serifFont) x = LeftMargin for line in statement.address.split(", "): painter.drawText(x, y, line) y += serifLineHeight y += serifLineHeight painter.drawText(x, y, "Dear {0},".format(statement.contact)) y += serifLineHeight balance = statement.balance() painter.drawText(x, y, "The balance of your account is $ {0:,.2f}".format(float(balance))) y += serifLineHeight if balance < 0: painter.setPen(Qt.red) text = "Please remit the amount owing immediately." else: text = ("We are delighted to have done business " "with you.") painter.drawText(x, y, text) painter.setPen(Qt.black) y += int(serifLineHeight * 1.5) painter.drawText(x, y, "Transactions:") y += serifLineHeight option = QTextOption(Qt.AlignRight|Qt.AlignVCenter) for date, amount in statement.transactions: x = LeftMargin h = int(fm.height() * 1.3) painter.drawRect(x, y, DateWidth, h) painter.drawText( QRectF(x + 3, y + 3, DateWidth - 6, h - 6), date.toString(DATE_FORMAT), option) x += DateWidth painter.drawRect(x, y, CreditWidth, h) text = "Credit" if amount < 0: text = "Debit" painter.drawText( QRectF(x + 3, y + 3, CreditWidth - 6, h - 6), text, option) x += CreditWidth painter.drawRect(x, y, AmountWidth, h) if amount < 0: painter.setPen(Qt.red) painter.drawText( QRectF(x + 3, y + 3, AmountWidth - 6, h - 6), "$ {0:,.2f}".format(float(amount)), option) painter.setPen(Qt.black) y += h y += serifLineHeight x = LeftMargin painter.drawText(x, y, "We hope to continue doing " "business with you,") y += serifLineHeight painter.drawText(x, y, "Yours sincerely") y += serifLineHeight * 3 painter.drawText(x, y, "K. Longrey, Manager") x = LeftMargin y = pageRect.height() - 72 painter.drawLine(x, y, pageRect.width() - LeftMargin, y) y += 2 font = QFont("Helvetica", 9) font.setItalic(True) painter.setFont(font) option = QTextOption(Qt.AlignCenter) option.setWrapMode(QTextOption.WordWrap) painter.drawText( QRectF(x, y, pageRect.width() - 2 * LeftMargin, 31), "The contents of this letter are for information " "only and do not form part of any contract.", option) page += 1 if page <= len(self.statements): self.printer.newPage() painter.restore() if __name__ == "__main__": app = QApplication(sys.argv) form = Form() form.show() app.exec_()
运行结果:
相关推荐:
python3+PyQt5实现支持多线程的页面索引器应用程序
以上是python3+PyQt5实现文档打印功能的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

如果在打开一份需要打印的文件时,在打印预览里我们会发现表格框线不知为什么消失不见了,遇到这样的情况,我们就要及时进行处理,如果你的打印文件里也出现了此类的问题,那么就和小编一起来学习下边的课程吧:excel打印表格框线消失怎么办?1、打开一份需要打印的文件,如下图所示。 2、选中所有需要的内容区域,如下图所示。 3、单击鼠标右键,选择“设置单元格格式”选项,如下图所示。 4、点击窗口上方的“边框”选项,如下图所示。 5、在左侧的线条样式中选择细实线图样,如下图所示。 6、选择“外边框”

豆包app里会有很多ai创作的功能,那么豆包app有什么功能呢?用户们可以通过这个软件来创作绘画,和ai进行聊天,还能够为用户生成文章,帮助大家搜索歌曲等。这篇豆包app功能介绍就能够告诉大家具体的操作方法,下面就是具体内容,赶紧看看吧!豆包app有什么功能答:可以绘画、聊天、写文、找歌。功能介绍:1、问题查询:可以通过ai来更快的找到问题的答案,什么样的问题都是可以询问。2、图片生成:可以有ai来为大家创建不同的图片,只需要告诉大家大概的要求。3、ai聊天:能够为用户们创建一个可以聊天的ai,

vivox100s和x100手机都是vivo手机产品线中的代表机型,它们分别代表了vivo在不同时间段内的高端技术水平,因此这两款手机在设计、性能和功能上均有一定区别。本文将从性能对比和功能解析两个方面对这两款手机进行详细比较,帮助消费者更好地选择适合自己的手机。首先,我们来看vivox100s和x100在性能方面的对比。vivox100s搭载了最新的

随着互联网的快速发展,自媒体这个概念已经深入人心。那么,自媒体到底是什么?它有哪些主要特点和功能呢?接下来,我们将一一探讨这些问题。一、自媒体到底是什么?自媒体,顾名思义,就是自己就是媒体。它是指通过互联网平台,个人或者团队可以自主创建、编辑、发布和传播内容的信息载体。不同于传统媒体,如报纸、电视、电台等,自媒体具有更强的互动性和个性化,让每个人都能成为信息的生产者和传播者。二、自媒体的主要特点和功能有哪些?1.低门槛:自媒体的崛起降低了进入媒体行业的门槛,不再需要繁琐的设备和专业的团队,一部手

随着小红书在年轻人中的流行,越来越多的人开始利用这一平台分享各方面的经验和生活见解。如何有效管理多个小红书账号成为一个关键问题。在本文中,我们将讨论一些小红书账号管理软件的功能,并探讨如何更好地经营小红书账号。随着社交媒体的发展,许多人发现自己需要管理多个社交账号。对于小红书用户来说,这也是一个挑战。一些小红书账号管理软件可以帮助用户更轻松地管理多个账号,包括自动发布内容、定时发布、数据分析等功能。通过这些工具,用户可以更高效地管理他们的账号,提高账号的曝光率和关注度。另一、小红书账号管理软件有

PHP技巧:快速实现返回上一页功能在网页开发中,经常会遇到需要实现返回上一页的功能。这样的操作可以提高用户体验,让用户更加方便地在网页之间进行导航。在PHP中,我们可以通过一些简单的代码来实现这一功能。本文将介绍如何快速实现返回上一页功能,并提供具体的PHP代码示例。在PHP中,我们可以使用$_SERVER['HTTP_REFERER']来获取上一页的URL

《探索Discuz:定义、功能及代码示例》随着互联网的迅猛发展,社区论坛已经成为人们获取信息、交流观点的重要平台。在众多的社区论坛系统中,Discuz作为国内较为知名的一种开源论坛软件,备受广大网站开发者和管理员的青睐。那么,什么是Discuz?它又有哪些功能,能为我们的网站提供怎样的帮助呢?本文将对Discuz进行详细介绍,并附上具体的代码示例,帮助读者更

我们有时候在使用PPT时经常会需要打印出来。可是,我们都知道PPT中的页数比较多,如果是一张一张的打印,实在是浪费呢?所以,本人亲测试过,一页纸上放6张PPT页面,然后双面打印是很OK的。既不浪费纸,排版内容也看的很清楚。那么,你知道怎么打印PPT一页6张双面呢?接下来,就叫你设置的方法,感兴趣的认真看哦!步骤详情:1、首先,我们在电脑上找到需要打印的PPT,然后双击打开。点击页面左侧上方按钮旁边的倒三角形符号,在下拉菜单中找到【文件】的按钮,点击一下;接着,在出现的信息中点击【打印】。2、点击
