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、點擊
