当前位置: 移动技术网 > IT编程>脚本编程>Python > python3+PyQt5实现文档打印功能

python3+PyQt5实现文档打印功能

2019年06月17日  | 移动技术网IT编程  | 我要评论

卞兰老公,hp拿走杯具踢飞茶几,tomnod

本文通过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_()

运行结果:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网