This article mainly introduces the document printing function of python3 PyQt5 in detail. It has certain reference value. Interested friends can refer to it.
This article adopts Python3 PyQt5 Implement the document printing function in Chapter 13 of the book "python Qt Gui Rapid Programming". This article uses three methods:
1. Use HTML and QTextDOcument to print documents
2. Use QTextCusor and QTextDocument to print documents
3. Use QPainter to print documents
Using Qpainter to print documents requires more care and complex calculations than QTextDocument, but QPainter does give full control over the output.
#!/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="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/153/291/f0f03360398e47554bc4a4fab2cf2da7-0.png?x-oss-process=image/resize,p_40" class="lazy" src=':/logo.png' alt="python3+PyQt5 implements document printing function" ></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_()
Run results:
python3 PyQt5 implements a page indexer application that supports multi-threading
python3 PyQt5 generic delegate detailed explanation
The above is the detailed content of python3+PyQt5 implements document printing function. For more information, please follow other related articles on the PHP Chinese website!

随着互联网的发展,人们越来越依赖网络,大部分时间都在使用各种各样的网站和应用程序,这也使得我们需要记住很多账号和密码。为了方便用户的使用,很多网站提供了自动登录功能,让用户免除频繁输入账号和密码的烦恼。本文将介绍使用JavaScript实现自动登录功能的方法。一、登录流程分析在开始实现自动登录功能之前,我们需要了解整个登录流程。一般情况下,一个网站的登录流程

PHP作为一款流行的后端编程语言,在Web开发领域广受欢迎。天气预报功能是一种常见的Web应用场景,基于PHP实现天气预报功能相对简单易懂。本文将介绍如何使用PHP实现天气预报功能。一、获取天气数据API要实现天气预报功能,首先需要获取天气数据。我们可以使用第三方天气API来获取实时、准确的天气数据。目前,国内主流的天气API供应商包括免费的“心知天气”和收

在Copilot目前在Windows11上拥有的少数功能中,也许最有用的功能是允许您交互和调整已复制到剪贴板的文本的功能。这使得将Copilot用作文本编辑和摘要工具变得容易,您可以直接从桌面使用。以下是您需要了解的有关使用Copilot在Windows上解释、修订、扩展和汇总文本的所有信息。如何在WindowsCopilot中使用复制的文本Copilot的预览版让我们第一次很好地了解了Windows对原生AI支持的集成。修改或扩展从其他地方复制的文本的早期功能之一可以通过内容创建、摘要、修订和

Apple今日释出了Safari技术预览173版本,涵盖部分可能于Safari17推出的功能。该版本适用于macOSSonoma测试版以及macOSVentura系统,有兴趣的用户可于官方网页下载。Safari技术预览173版于设定中新增了功能标志区块,取代原先开发菜单的实验功能。该区块可让开发者快速地搜索特定功能,并以不同形式将「稳定」、「可供测试」、「预览」或「开发人员」等状态标示出来。重新设计的开发菜单可以帮助创作者更容易找到关键工具,以便建立网页、网页应用程序、其他应用程序中的网页内容、

GoogleColab是一个自2017年以来一直在促进Python编程的平台,它将利用Google的高级代码模型Codey引入AI编码功能。Codey基于PaLM2模型构建,对来自外部来源的大型高质量代码数据集进行了精心微调,以提高其在编码任务方面的性能。Colab即将推出的功能包括代码补全、自然语言到代码生成以及代码辅助聊天机器人。最初的重点将放在代码生成上,该功能旨在使用户能够生成更大的代码块并从注释或提示编写整个函数。这旨在减少编写重复代码的需求,允许用户专注于编程和数据科学的更复杂的方面

Apple在设备中内置了这个方便的功能,可以从iPhone上的相机轻松访问它,这将允许您自动扫描设备上的QR码。二维码代表快速响应码,本质上是一种二维条形码,可以通过配备内置摄像头的各种智能手机和其他电子设备轻松扫描和解释。扫描二维码后,用户通常会被定向到特定网站或提示激活应用程序中的特定功能。这种令人难以置信的方便功能在现代智能手机(包括Apple的iPhone)中变得越来越普遍,它是用户以最小的努力访问信息,服务或功能的便捷方式。许多公司在实体产品上使用此功能,您可以扫描其产品上的二维码,然

鸿蒙os3.0目前正在测试阶段,很快用户就将迎来新的系统体验了,那么相较于2.0版本,鸿蒙os3.0有什么功能呢?华为鸿蒙3.0包含了多屏协同、性能共享等功能,用户可以获得更加完善的协同体验,同时也能提升手机运行大型游戏或软件的流畅度。另外,它简化了小窗交互方式,并改进通知栏,带给你更为完美的体验,接下来就让小编给大家分析一下华为鸿蒙3.0新功能介绍,一起来了解一下吧。华为鸿蒙3.0功能介绍1、多屏协同:此前鸿蒙2.0可以在电脑手机之间互相切换使用,提高了用户的工作效率和使用体验,但此次的鸿蒙3

win10系统是目前主流的操作系统,也是微软最新的产品,版本很多。其中有网友纠结不知道选择win10纯版还是win10专业版,win10电脑系统纯版和专业版有什么区别。以下小系列将告诉你win10电脑系统纯版和专业版的区别。win10纯版:Win10纯版是网上第三方系统爱好者,在微软原版系统的基础上删除一些自带广告封装的系统。没有多余的软件捆绑,但稳定性可能没有正式版和专业版那么强。最重要的是win10纯版可以在网上下载安装,由民间专家优化,完全免费,功能和专业版没有太大区别。win10专业版:


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 Linux new version
SublimeText3 Linux latest version

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!
