PYTHON3+PYQT5 for document printing functions

Source: Internet
Author: User
Tags drawtext
This article is mainly for you to introduce the PYTHON3+PYQT5 implementation of document printing function, with a certain reference value, interested in small partners can refer to

In this paper, the "Python Qt Gui Rapid Programming" book 13 document printing function is realized through python3+pyqt5 . This article is a total of three ways:

1. Print documents using HTML and Qtextdocument
2. Print documents using Qtextcusor and Qtextdocument
3. Print documents using Qpainter

Using Qpainter to print a document requires more worrying and complex calculations than qtextdocument, but Qpainter does give you full control over the output.

#!/usr/bin/env python3import mathimport sysimport htmlfrom pyqt5.qtprintsupport Import Qprinter,qprintdialogfrom 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_resource Sfrom pyqt5.qtprintsupport Import qprinter,qprintdialogfrom 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, QTextTabl Eformat, qpixmap,qtextblockformat) Import Qrc_resourcesdate_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 (s ELF): return sum ([Amount for date, amount-self.transactions]) class Form (Qdialog): Def __init__ (self, parent=none): Supe R (Form, self). __init__ (parent) Self.printer = Qprinter () self.printer.setPageSize (Qprinter.letter) Self.generatefakestatements () self.table = Qtablewidget () self.populatetable () Cursorbutton = QPushButton ("Print via Q& Amp Cursor ") HtmlButton = Qpushbutton (" Print via &html ") Painterbutton = Qpushbutton (" Print via Q&painter ") Quitbutto n = 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), 2 342)) Statement.transactions.append ((Qdate (9, 9, 10), 2342)) Statement.transactions.append ((Qdate () (+ (2007)), 2352) Statement.transactions.append ((Qdate (12, -1500)) Statement.transactions.append ((Qdate (2007, 11,) , 2352)) Statement.transactions.append ((Qdate (2007, 20), 2352)) Statement.transactions.append ((Qdate (+ 12) (+/--) (+/-) (+/-(+)) , -7500)) Statement.transactions.append ((Qdate (+, 1,)) Statement.transactions.append ((Qdate (2008, 10), 2362) Self.statements.append (statement) statement = statement ("Demamitur Plc", "Mr G. Brown", "Tall Towers, Tower Ham" Lets, London, WC1 3BX ") Statement.transactions.append ((Qdate (2007, 5, 871)) Statement.transactions.append ((Qdate (7, 6, 2007), 542)) Statement.transactions.append (1123)) Statement.transactions.append ((Qdate (7, -1928)) Statement.transactions.append ((Qdate (2007, 8, ( -214)) Statement.transactions.append ((Qdate (9, -3924)) Statement.transactions.append ((Qdate (2007, 9, , 2712)) Statement.transactions.append ((Qdate (9, 2007), -273)) #statement. Transactions.append ((Qdate (11), 8), -728)) #statement. Transactions.append ((Qdate (2, 7), 228)) #statement. Transactions.append ((Qdate (2008, 3, 13) , -508)) #statement. Transactions.append ((Qdate (3,), -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 (s  tatement.address). Replace (",", "<br>") Contact = Html.escape (statement.contact) balance = Statement.balance ()   HTMLText + = ("<p align=right></p>" "<p Align=right>greasy Hands Ltd." "<br>new Lombard Street" "<br>london<br>wc13 4px<br>{0}</p>" "<p>{1}</p>& Lt;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&gt ; Please remit the "amount owing immediately.</b></font>") Else:htmltext + = ("We are delighted  Done Business "with you.") HTMLText + = ("</p><p> </p><p>" "<table border=1 cellpadding=2" "Cellspacing=2><tr&gt  ; &LT;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></t D></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,&LT;BR&GT Yours sincerely, "" <br><br>k Longrey, manager</p> ") dialog = Qprintdialog (Self.printer, self) if dial OG.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 = QTe Xtblockformat (BodyFormat) lastparabodyformat.setpagebreakpolicy (Qtextformat.pagebreak_alwaysafter) Rightbodyformat = Qtextblockformat () rightbodyformat.setalignment (qt.alignright) Headcharformat = QTextCharFormat () Headcharformat.setfont (Qfont ("Helvetica", ten)) Bodycharformat = Qtextcharformat () Bodycharformat.setfont (QFont (" Times ", one)) 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 (DA Te_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 the 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 the" Business WI  th 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.cel LAt (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:FO Rmat = 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) de F Printviaqpainter (Self): Dialog = Qprintdialog (Self.printer, self) if not dialog.exec_ (): Return LeftMargin = Sansfon t = Qfont ("Helvetica", "ten") Sanslineheight = Qfontmetrics (sansfont). Height () Seriffont = Qfont ("Times", one) FM = Qfontmetri CS (seriffont) datewidth = Fm.width ("September, 2999") Creditwidth = Fm.width ("credit") Amountwidth = Fm.width ("W99 9999.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.drawpixma P (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.currentdat E (). 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 AMO  Unt owing immediately. "  Else:text = ("We are delighted to has done business" "with you.") Painter.drawtext (x, y, text) painter.setpen (qt.black) y + = Int (Seriflineheight * 1.5) Painter.drawtext (x, y, "transacti ONS: ") y + = seriflineheight option = qtextoption (qt.alignright| Qt.alignvcenter) for date, amount in statement.transactions:x = LeftMargin h = Int (fm.height () * 1.3) Painter.drawrec T (x, Y, Datewidth, h) painter.drawtext (QRECTF (x + 3, y + 3, DateWidth-6, h-6), date.tostring (Date_format), Optio N) x + = Datewidth painter.drawrect (x, Y, Creditwidth, h) Text = "Credit" if amount < 0:text = "Debit" PAINTER.D Rawtext (QRECTF (x + 3, y + 3, CreditWidth-6, h-6), text, option) x + = Creditwidth painter.drawrect (x, Y, AMOUNTW Idth, 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 = Leftmargi  N y = pagerect.height ()-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.wo Rdwrap) Painter.drawtext (QRECTF (x, Y, Pagerect.width ()-2 * LeftMargin, +), "The contents of this letter is for I Nformation "" Only and don't form part of any contract. ", option) page + = 1 if page <= len (self.statements): SE Lf.printer.newPage () Painter.restore () if __name__ = = "__main__": App = Qapplication (sys.argv) Form = form () form.show () a PP.EXEC_ ()

Operation Result:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.