python3+PyQt5实现文档打印功能


Posted in Python onApril 24, 2018

本文通过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实现文档打印功能

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
探寻python多线程ctrl+c退出问题解决方案
Oct 23 Python
python使用calendar输出指定年份全年日历的方法
Apr 04 Python
在Python的struct模块中进行数据格式转换的方法
Jun 17 Python
Python中内建函数的简单用法说明
May 05 Python
Python实现求笛卡尔乘积的方法
Sep 16 Python
Python进度条实时显示处理进度的示例代码
Jan 30 Python
python 循环读取txt文档 并转换成csv的方法
Oct 26 Python
Python Django框架实现应用添加logging日志操作示例
May 17 Python
使用keras实现孪生网络中的权值共享教程
Jun 11 Python
Python Switch Case三种实现方法代码实例
Jun 18 Python
解决python对齐错误的方法
Jul 16 Python
分析Python list操作为什么会错误
Nov 17 Python
Python结合ImageMagick实现多张图片合并为一个pdf文件的方法
Apr 24 #Python
python3+PyQt5实现柱状图
Apr 24 #Python
python3+PyQt5自定义视图详解
Apr 24 #Python
python自动重试第三方包retrying模块的方法
Apr 24 #Python
python3+PyQt5泛型委托详解
Apr 24 #Python
python去除扩展名的实例讲解
Apr 23 #Python
python3 遍历删除特定后缀名文件的方法
Apr 23 #Python
You might like
php中配置文件操作 如config.php文件的读取修改等操作
2012/07/07 PHP
如何给phpcms v9增加类似于phpcms 2008中的关键词表
2013/07/01 PHP
php中file_get_content 和curl以及fopen 效率分析
2014/09/19 PHP
Laravel5.7 数据库操作迁移的实现方法
2019/04/12 PHP
JS代码格式化和语法着色V2
2006/10/14 Javascript
javascript 事件查询综合 推荐收藏
2010/03/10 Javascript
Javascript 静态页面实现随机显示广告的办法
2010/11/17 Javascript
HTML颜色选择器实现代码
2010/11/23 Javascript
js分解url参数(面向对象-极简主义法应用)
2012/08/09 Javascript
javascript-表格排序(降序/反序)实现介绍(附图)
2013/05/30 Javascript
Extjs3.0 checkboxGroup 动态添加item实现思路
2013/08/14 Javascript
jquery实现仿Flash的横向滑动菜单效果代码
2015/09/17 Javascript
jQuery 选择符详细介绍及整理
2016/12/02 Javascript
Bootstrap面板使用方法
2017/01/16 Javascript
jquery radio 动态控制选中失效问题的解决方法
2018/02/28 jQuery
uniapp实现横向滚动选择日期
2020/10/21 Javascript
[40:56]2018DOTA2亚洲邀请赛 3.31 小组赛 A组 Liquid vs TNC
2018/04/01 DOTA
Mac OS X10.9安装的Python2.7升级Python3.3步骤详解
2013/12/04 Python
使用python编写脚本获取手机当前应用apk的信息
2014/07/21 Python
在Windows服务器下用Apache和mod_wsgi配置Python应用的教程
2015/05/06 Python
高质量Python代码编写的5个优化技巧
2017/11/16 Python
python实现图像识别功能
2018/01/29 Python
pandas把dataframe转成Series,改变列中值的类型方法
2018/04/10 Python
Python中时间datetime的处理与转换用法总结
2019/02/18 Python
pytorch 状态字典:state_dict使用详解
2020/01/17 Python
基于Python绘制美观动态圆环图、饼图
2020/06/03 Python
Python xlwings插入Excel图片的实现方法
2021/02/26 Python
Mistine官方海外旗舰店:泰国国民彩妆品牌
2016/12/28 全球购物
马来西亚综合购物网站:Lazada马来西亚
2018/06/05 全球购物
英国创新设计文具、卡片和礼品包装网站:Paperchase
2018/07/14 全球购物
药店主任岗位责任制
2014/02/10 职场文书
《童趣》教学反思
2014/02/19 职场文书
公司合作协议范文
2014/10/01 职场文书
国博复兴之路观后感
2015/06/02 职场文书
法制工作总结2015
2015/07/23 职场文书
领导干部学习十八届五中全会精神心得体会
2016/01/05 职场文书