def handlePaintRequest(self, printer): # find empty cells for row in range(self.tableView.rowCount()): for column in range(self.tableView.columnCount()): myitem = self.tableView.item(row, column) if myitem is None: item = QTableWidgetItem("") self.tableView.setItem(row, column, item) printer.setDocName(self.fname) document = QTextDocument() cursor = QTextCursor(document) model = self.tableView.model() tableFormat = QTextTableFormat() tableFormat.setBorder(0.2) tableFormat.setBorderStyle(3) tableFormat.setCellSpacing(0) tableFormat.setTopMargin(0) tableFormat.setCellPadding(4) table = cursor.insertTable(model.rowCount(), model.columnCount(), tableFormat) for row in range(table.rows()): for column in range(table.columns()): cursor.insertText(self.tableView.item(row, column).text()) cursor.movePosition(QTextCursor.NextCell) document.print_(printer)
def handlePaintRequest(self, printer): printer.setDocName(self.fname) document = QTextDocument() cursor = QTextCursor(document) model = self.tableView.model() tableFormat = QTextTableFormat() tableFormat.setBorder(0.2) tableFormat.setBorderStyle(3) tableFormat.setCellSpacing(0) tableFormat.setTopMargin(0) tableFormat.setCellPadding(4) table = cursor.insertTable(model.rowCount() + 1, model.columnCount(), tableFormat) model = self.tableView.model() ### get headers myheaders = [] for i in range(0, model.columnCount()): myheader = model.headerData(i, Qt.Horizontal) cursor.insertText(str(myheader)) cursor.movePosition(QTextCursor.NextCell) ### get cells for row in range(0, model.rowCount()): for col in range(0, model.columnCount()): index = model.index(row, col) cursor.insertText(str(index.data())) cursor.movePosition(QTextCursor.NextCell) document.print_(printer)
def handlePaintRequest(self,printer): """ This is the backbone main function that handles all the print functions PrintPreview and PrintCsv . This handles all the required operations like bolding the header labels and all the other things like moving the cursor for each cell row and column wise and finally printing to document. :param printer: :return: """ document = QTextDocument() cursor = QTextCursor(document) table = cursor.insertTable(self.tableWidget.rowCount(), self.tableWidget.columnCount()) fm = QTextCharFormat() font = QFont() font.setBold(True) font.setUnderline(True) fm.setFont(font) for i in range(self.tableWidget.columnCount()): col = self.tableWidget.horizontalHeaderItem(i).text() if col is not None: cursor.insertText(col,fm) cursor.movePosition(QTextCursor.NextCell) for row in range(self.tableWidget.rowCount()): for col in range(self.tableWidget.columnCount()): w = self.tableWidget.cellWidget(row, col) it = self.tableWidget.item(row, col) if w is not None: cursor.insertText(self.get_text_from_widget(w)) elif it is not None: cursor.insertText(it.text()) cursor.movePosition(QTextCursor.NextCell) document.print_(printer)
def printHtml(printer): html = """<html> <head></head> <body> <h1>55555</h1><b>bold</b><h1>55555</h1><b>bold</b> <h1>55555</h1><b>bold</b> <h1>55555</h1><b>bold</b><h1>55555</h1><b>bold</b> <h1>55555</h1><b>bold</b> <h1>55555</h1><b>bold</b> <h1>55555</h1><b>bold</b> <h1>55555</h1><b>bold</b> <h1>55555</h1><b>bold</b> <h1>55555</h1><b>bold</b> <h1>55555</h1><b>bold</b><h1>55555</h1><b>bold</b> <h1>55555</h1><b>bold</b> <h1>55555</h1><b>bold</b> <h1>55555</h1><b>bold</b> <h1>55555</h1><b>bold</b><h1>55555</h1><b>bold</b> <h1>55555</h1><b>bold</b> <h1>55555</h1><b>bold</b> <h1>55555</h1><b>bold</b> <h1>55555</h1><b>bold</b> </body> </html>""" textDocument = QTextDocument() textDocument.setHtml(html) # textDocument.print(printer) textDocument.print_(printer)
def printReciept(self, htmltext): dialog = QPrintDialog(self.printer, self) if dialog.exec_(): document = QTextDocument() # print(self.printer.logicalDpiX()) # print(self.printer.logicalDpiX() * (210 / 25.4)) # print(self.printer.logicalDpiY()) # print(self.printer.logicalDpiY() * (297 / 25.4)) #A4 # document.setPageSize(QSizeF(self.printer.logicalDpiX() * (210 / 25.4),self.printer.logicalDpiY() * (297 / 25.4))); #小票 qsizeF = QSizeF(self.printer.logicalDpiX() * (257 / 25.4), self.printer.logicalDpiY() * (125 / 25.4)) # qsizeF = QSizeF(self.printer.logicalDpiX() * (215.90 / 25.4), self.printer.logicalDpiY() * (127.00 / 25.4)); # qsizeF = QSizeF(self.printer.logicalDpiY() * (125 / 25.4),self.printer.logicalDpiX() * (257 / 25.4)); self.printer.setPageSize(QPrinter.Custom) self.printer.setPaperName("小票2") paperSize = QSizeF(257, 125) self.printer.setPaperSize(paperSize, QPrinter.Millimeter) # self.printer.setPageSizeMM(qsizeF) document.setPageSize(qsizeF) # font = QFont(); # font.setPointSize(6) # document.setDefaultFont(font); document.setHtml(htmltext) document.print_(self.printer)
def printViaHtml(self, htmltext): dialog = QPrintDialog(self.printer, self) if dialog.exec_(): document = QTextDocument() # print(self.printer.logicalDpiX()) # print(self.printer.logicalDpiX() * (210 / 25.4)) # print(self.printer.logicalDpiY()) # print(self.printer.logicalDpiY() * (297 / 25.4)) # document.setPageSize(QSizeF(self.printer.logicalDpiX() * (210 / 25.4), # self.printer.logicalDpiY() * (297 / 25.4))); document.setHtml(htmltext) document.print_(self.printer)
def print_html(cls, parent, html): from PyQt5.QtPrintSupport import QPrinter, QPrintDialog from PyQt5.QtGui import QTextDocument printer = QPrinter(QPrinter.HighResolution) dialog = QPrintDialog(printer, parent) result = dialog.exec_() if result == dialog.Accepted: doc = QTextDocument() doc.setHtml(html) doc.print_(printer) return result
def savePdf(self,fileName): pt = QPdfWriter(fileName) # pt.logicalDpiX pt.setPageSize(QPagedPaintDevice.A4) # print('resolution',pt.resolution()) pt.setResolution(10000) # print('resolution',pt.resolution()) textDocument = QTextDocument() textDocument.setHtml(self.pcontext.thtmlGet()) textDocument.print_(pt) textDocument.end() print('pdf creat = ',fileName)
def gerarPDF(arquivo_html, caminho): from PyQt5.QtGui import QTextDocument from PyQt5.QtPrintSupport import QPrinter doc = QTextDocument() html = open(arquivo_html).read() doc.setHtml(html) printer = QPrinter() printer.setOutputFileName(caminho) printer.setOutputFormat(QPrinter.PdfFormat) printer.setPageSize(QPrinter.A4) doc.print_(printer) os.startfile(caminho)
def print_func(self): from PyQt5.QtPrintSupport import QPrintDialog dialog = QPrintDialog() from PyQt5.QtGui import QTextDocument doc = QTextDocument() doc.setHtml(self.bill_html) if dialog.exec_() == QPrintDialog.Accepted: doc.print_(dialog.printer()) self.history_class.MW.mess('Printing Done') else: self.history_class.MW.mess('Printing Rejected')
def init_print(self, linenos=True, style="default"): app = QApplication([]) # noqa doc = QTextDocument() doc.setHtml(self.highlight_file(linenos=linenos, style=style)) printer = QPrinter() printer.setOutputFileName(self.pdf_file) printer.setOutputFormat(QPrinter.PdfFormat) page_size_dict = { "a2": QPrinter.A2, "a3": QPrinter.A3, "a4": QPrinter.A4, "letter": QPrinter.Letter } printer.setPageSize(page_size_dict.get(self.size.lower(), QPrinter.A4)) printer.setPageMargins(15, 15, 15, 15, QPrinter.Millimeter) doc.print_(printer) logging.info("PDF created at %s" % (self.pdf_file))
def handlePaintRequest(self, printer): document = QTextDocument() document.setPageSize(QSizeF(printer.pageRect().size())) cursor = QTextCursor(document) tableFormat = QTextTableFormat() TableText = QTextCharFormat() TableText.setLayoutDirection(Qt.RightToLeft) # tableFormat.setAlignment(Qt.AlignCenter) tableFormat.setBackground(QColor('#d3fbf5')) tableFormat.setCellPadding(3) tableFormat.setCellSpacing(4) tableFormat.setLayoutDirection(Qt.RightToLeft) tableFormat.setBorderStyle(QTextTableFormat.BorderStyle_Double) TitrFormat = QTextCharFormat() fontTitr = QFont() fontTitr.setBold(True) TitrFormat.setFont(fontTitr) SotonFormat = QTextCharFormat() TitrFormat.setLayoutDirection(Qt.RightToLeft) # SotonFormat.setBackground(QColor('#EEF9C9')) SotonFormat.setFont(fontTitr) cursor.insertText(self.TableTitr + "\n", TitrFormat) model = self.ui.tableView_result.model() table = cursor.insertTable(model.rowCount() + 1, model.columnCount(), tableFormat) headers = [ 'پلاک', 'بخش', 'تعداد جلد', 'تعداد صفحات', 'نوع', 'همکار تقاضاکننده', 'تحویل گیرنده', 'علت درخواست', 'توضیحات', 'تاریخ تحویل', 'ساعت تحویل', 'تاریخ بازگشت', 'ساعت بازگشت' ] self.tableResult.insertRows(10, 10) for header in reversed(headers): cursor.insertText(header, SotonFormat) cursor.movePosition(QTextCursor.NextCell) for row in range(table.rows()): for column in reversed(range(table.columns())): cursor.insertText( self.tableResult.data(self.tableResult.index(row, column)), TableText) cursor.movePosition(QTextCursor.NextCell) cursor.movePosition(QTextCursor.NextBlock) cursor.insertText('- سامانه بایگانی ثبت ماسال -', TitrFormat) # printer.setFullPage(True) document.print_(printer)
def create_pdf(filename='foo.pdf', model=None): infos_centre = model.get_infos() doc = QTextDocument() title = '<h1>Rapport comptable du séjour ' + infos_centre[ 'centre'] + '</h1>' about = '<div id="about">' + create_about() + '</div>' logo = '<img src="design/logo.png" align="right"/>' infos = '<div id="infos">' + create_infos_table(model) + '</div>' general = '<div id="general">' + create_general_infos(model) general += create_general(model) + '</div>' html = '<body>' + logo + title + about + infos + general + '</body>' doc.setHtml(html) printer = QPrinter() printer.setOutputFileName(filename) printer.setOutputFormat(QPrinter.PdfFormat) printer.setPageSize(QPrinter.A4) doc.print_(printer)
def printing_bill(): from backend import CommonFunctions data_to_print = CommonFunctions().convert_to_bill( var.th_fetch_bill.bill_doc, var.th_fetch_bill.fetch_dict) from PyQt5.QtPrintSupport import QPrintDialog dialog = QPrintDialog() from PyQt5.QtGui import QTextDocument doc = QTextDocument() doc.setHtml(data_to_print) if dialog.exec_() == QPrintDialog.Accepted: doc.print_(dialog.printer()) MW.mess('Printing Done') else: MW.mess('Printing Rejected')
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 print_proof(self): printer = QPrinter(96) printer.setOrientation(QPrinter.Landscape) printer.setOutputFileName('tmp.pdf') printer.setPageMargins(16, 12, 20, 12, QPrinter.Millimeter) text = "Date:\n{}\n\n".format(time.strftime("%d/%m/%Y")) text += "Address:\n{}\n\n".format(self.api.get_main_address()) text += "Current Blockhash:\n{}".format(self.api.get_actual_hash()) document = QTextDocument() document.setPageSize(QSizeF(printer.pageRect().size())) document.setDefaultFont(QFont("Arial", 30)) document.setPlainText(text) dialog = QPrintDialog() if dialog.exec_() == QDialog.Accepted: dialog.printer().setOrientation(QPrinter.Landscape) document.print_(dialog.printer())
def print(self): html = HTML table = TABLE for key, _ in self._boardPins: row = ROW variable = '-' initial = '-' low = '-' high = '-' if key in self._propPins: variable = self._propPins[key].getVariable() if self._propPins[key].getInitial(): initial = 'HIGH' else: initial = 'LOW' high, low = self._propPins[key].getAlias() row = row.replace('{{OUTPUT}}', key) row = row.replace('{{VARIABLE}}', variable) row = row.replace('{{INITIAL}}', initial) row = row.replace('{{HIGH}}', low) row = row.replace('{{LOW}}', high) table = table.replace('{{ROWS}}', row + "\n{{ROWS}}") table = table.replace('{{ROWS}}', "") title = TITLE title = title.replace('{{PROP}}', self._propSettings['prop']['prop_name']) title = title.replace('{{FILE}}', self._localFile) body = title body = body + table html = html.replace('{{BODY}}', body) doc = QTextDocument() doc.setHtml(html) printer = QPrinter() dialog = QPrintDialog(printer) if dialog.exec_() == True: doc.print_(printer)
def run(self): try: sys.stdout = FakeStd() sys.stderr = FakeStd() app = QApplication.instance() if app is None: app = QApplication(['--platform', 'minimal']) # we need this call to correctly render images... app.processEvents() printer = QPrinter() if self.printer_name: printer.setPrinterName(self.printer_name) # printer.setResolution(96) text_document = QTextDocument() printer.setFullPage(True) printer.setPageMargins( self.margin_left, self.margin_top, self.margin_right, self.margin_bottom, QPrinter.Millimeter ) page_size = QSizeF() page_size.setHeight(printer.height()) page_size.setWidth(printer.width()) text_document.setPageSize(page_size) text_document.setDocumentMargin(0.0) text_document.setHtml(self.html) text_document.print_(printer) except Exception as e: logging.error(str(e))
class FinalTable(QFormLayout): def __init__(self): super().__init__() # Создание строк в итоговой таблице для каждого типа материала и услуг self.p_row = QLineEdit() self.fs_row = QLineEdit() self.o_row = QLineEdit() self.fp_row = QLineEdit() self.s_row = QLineEdit() self.delivery_row = QLineEdit() self.delivery_row.textChanged.connect(self.set_final_price_row) self.lifting_row = QLineEdit() self.lifting_row.textChanged.connect(self.set_final_price_row) self.measurement_row = QLineEdit() self.measurement_row.textChanged.connect(self.set_final_price_row) self.project_row = QLineEdit() self.project_row.textChanged.connect(self.set_final_price_row) self.sum_row = QLineEdit() self.final_price_row = QLineEdit() self.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow) self.row_dict = { 1: self.p_row, 2: self.fs_row, 3: self.o_row, 4: self.fp_row, 5: self.s_row, } self.additional_row_dict = { 1: self.delivery_row, 2: self.lifting_row, 3: self.measurement_row, 4: self.project_row } # Делаем каждую строку неизменяемой for key in self.row_dict: self.row_set_read_only(key) row = self.row_dict.get(key) row.setText("0 руб.") self.sum_row.setText("0 руб.") self.sum_row.setReadOnly(True) self.set_sum_row() self.production_layout = QHBoxLayout() self.production_percent = QLineEdit() self.production_result = QLineEdit() self.production_result.setReadOnly(True) self.production_percent.setPlaceholderText("Введите %") self.production_percent.textChanged.connect( lambda: self.set_prod_result(self.production_percent.text())) self.production_percent.textChanged.connect(self.set_final_price_row) self.production_layout.addWidget(self.production_percent) self.production_layout.addWidget(self.production_result) self.final_price_row.setText("0 руб.") self.final_price_row.setReadOnly(True) self.clear_button = QPushButton("Отчистить") self.clear_button.clicked.connect(self.clear_final_table) self.clear_button.clicked.connect(clear_all) self.create_pdf = QPushButton("Сохранить в PDF") self.create_pdf.clicked.connect(self.set_pdf_table) self.create_pdf.clicked.connect(self.create_pdf_file) self.tech_rows_layout = QHBoxLayout() self.tech_rows_layout.addWidget(self.create_pdf) self.tech_rows_layout.addWidget(self.clear_button) self.text = QTextDocument() self.add_rows() def add_rows(self): self.addRow("Плитные материалы", self.p_row) self.addRow("Фурнитура стандарт", self.fs_row) self.addRow("Освещение", self.o_row) self.addRow("Фурнитура премиум", self.fp_row) self.addRow("Столярные изделия", self.s_row) self.addRow("Итоговая стоимость изделия", self.sum_row) self.addRow("Доставка", self.delivery_row) self.addRow("Подъем на этаж на лифте", self.lifting_row) self.addRow("Изготовление, сборка, монтаж", self.production_layout) self.addRow("Замер", self.measurement_row) self.addRow("Проект", self.project_row) self.addRow("Итоговая стоимость изделия и услуг", self.final_price_row) self.addRow(self.tech_rows_layout) def row_set_read_only(self, row_type=1): row = self.row_dict.get(row_type) row.setReadOnly(True) def set_row(self, calc=0, material_type=1): # Вывод в таблицу значения итоговой стоимости материала определенного типа row = self.row_dict.get(material_type) row.setText(str(int(calc)) + " руб.") # Вывод в таблицу значения итоговой стоимости только материалов, без учёта услуг def set_sum_row(self): total = 0 for key in self.row_dict: row = self.row_dict.get(key).text() line = row.split(" ") total += float(line[0]) self.sum_row.setText(str(total) + " руб.") # Вывод в таблицу значения итоговой стоимости всего изделия def set_final_price_row(self): final = 0 for key in self.additional_row_dict: row_text = self.additional_row_dict.get(key).text() try: final += float(row_text) except ValueError: input_check(self.additional_row_dict.get(key)) materials_sum = self.sum_row.text().split() final += float(materials_sum[0]) f = self.production_result.text().split() try: final += float(f[0]) except IndexError: pass except ValueError: pass self.final_price_row.setText(str(final) + " руб.") def set_prod_result(self, production_percent): try: # Обработка случая, когда пользователь пытается ввести дробное число через запятую, а не через точку percent_num = production_percent.split(',') if len(percent_num) > 1: percent_decimal = float(percent_num[1]) while percent_decimal > 1: percent_decimal = percent_decimal / 10 production_percent = float(percent_num[0]) + percent_decimal percent = float(production_percent) / 100 materials_sum = self.sum_row.text().split() self.production_result.setText( str("{0:.1f}".format(float(materials_sum[0]) * percent))) self.production_percent.setStyleSheet(stylesheet) except ValueError: if self.production_percent.text().strip() == "": self.production_percent.setStyleSheet(stylesheet) else: self.production_percent.setStyleSheet( "border-style: solid; border-width: 2px; border-color: red" ) self.production_result.setText("") # Отчистить итоговую таблицу def clear_final_table(self): for key in self.row_dict: self.row_dict.get(key).setText("0 руб.") for key in self.additional_row_dict: self.additional_row_dict.get(key).setText("") self.production_percent.setText("") self.set_sum_row() self.set_final_price_row() # Создание pdf файла def create_pdf_file(self): file_name, _ = QFileDialog.getSaveFileName(self.create_pdf, 'Сохранить в PDF', None) if file_name != '': if QFileInfo(file_name).suffix() == "": file_name += '.pdf' printer = QPrinter(QPrinter.HighResolution) printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(file_name) self.text.print_(printer) # Заполнение HTML таблицы из файла table.py def set_pdf_table(self): html_format = html.format( p_row=self.p_row.text(), fs_row=self.fs_row.text(), o_row=self.o_row.text(), fp_row=self.fp_row.text(), s_row=self.s_row.text(), sum_row=self.sum_row.text(), delivery_row=self.delivery_row.text(), lifting_row=self.lifting_row.text(), production_result=self.production_result.text(), measurement_row=self.measurement_row.text(), project_row=self.project_row.text(), final_price_row=self.final_price_row.text()) self.html = html_format self.text.setHtml(self.html)
def CreatePDF(self, out, timestamp, data, frame, rows, columns, fileName, VManager): ''' Create PDF QgsTask ''' QCoreApplication.processEvents() QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) font_normal = QFont("Helvetica", 10, QFont.Normal) font_bold = QFont("Helvetica", 12, QFont.Bold) printer = QPrinter(QPrinter.HighResolution) printer.setOrientation(QPrinter.Portrait) printer.setOutputFormat(QPrinter.PdfFormat) printer.setFullPage(True) printer.setPaperSize(QPrinter.A4) printer.setOutputFileName(out) printer.setPageMargins(15, 15, 15, 15, QPrinter.Point) printer.setColorMode(QPrinter.Color) document = QTextDocument() document.setDefaultFont(font_normal) cursor = QTextCursor(document) cursor.movePosition(QTextCursor.Start, QTextCursor.MoveAnchor) cursor.insertHtml(""" <p style='text-align: center;'> <img style='display: block; margin-left: auto; margin-right: auto;' src=\':/imgFMV/images/header_logo.png\' width='200' height='25' /> </p> <p style='text-align: center;'> <strong>Video : </strong>%s<strong> </p> <p style='text-align: center;'> <strong>TimeStamp : </strong>%s</p><br><br> """ % (fileName, timestamp)) tableFormat = QTextTableFormat() tableFormat.setHeaderRowCount(1) tableFormat.setBorderBrush(QBrush(Qt.black)) tableFormat.setAlignment(Qt.AlignHCenter) tableFormat.setCellPadding(2) tableFormat.setCellSpacing(2) centerFormat = QTextBlockFormat() centerFormat.setAlignment(Qt.AlignCenter) cursor.insertBlock(centerFormat) textTable = cursor.insertTable(rows + 1, columns, tableFormat) tableHeaderFormat = QTextCharFormat() tableHeaderFormat.setFont(font_bold) tableHeaderFormat.setBackground(QColor("#67b03a")) tableHeaderFormat.setForeground(Qt.white) alternate_background = QTextCharFormat() alternate_background.setBackground(QColor("#DDE9ED")) for column in range(columns): cell = textTable.cellAt(0, column) cell.setFormat(tableHeaderFormat) cellCursor = cell.firstCursorPosition() cellCursor.insertText(VManager.horizontalHeaderItem(column).text()) row = 0 for key in sorted(data.keys()): cell0 = textTable.cellAt(row + 1, 0) cell1 = textTable.cellAt(row + 1, 1) cell2 = textTable.cellAt(row + 1, 2) if (row + 1) % 2 == 0: cell0.setFormat(alternate_background) cell1.setFormat(alternate_background) cell2.setFormat(alternate_background) cellCursor0 = cell0.firstCursorPosition() cellCursor0.insertText(str(key)) cellCursor1 = cell1.firstCursorPosition() cellCursor1.insertText(str(data[key][0])) cellCursor2 = cell2.firstCursorPosition() cellCursor2.insertText(str(data[key][1])) row += 1 cursor.movePosition(QTextCursor.End, QTextCursor.MoveAnchor) cursor.insertHtml(""" <br><p style='text-align: center;'><strong>Current Frame</strong></p><br> """) centerFormat = QTextBlockFormat() centerFormat.setAlignment(Qt.AlignHCenter) cursor.insertBlock(centerFormat) cursor.insertImage(frame.scaledToWidth(500)) QCoreApplication.processEvents() document.print_(printer) QCoreApplication.processEvents()
def SaveAsPDF(self): """ Save Table as pdf """ fileName, _ = QFileDialog.getSaveFileName(self, "Save File", "", "PDF Files (*.pdf)") if fileName == "": return try: videoName = self.player.fileName timestamp = self.player.player.position() QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) rows = self.VManager.rowCount() columns = self.VManager.columnCount() printer = QPrinter(QPrinter.HighResolution) innerRect = printer.pageRect() sizeF = QSizeF(innerRect.size().width(), innerRect.size().height()) header = QTextDocument() header.setPageSize(sizeF) cursor_header = QTextCursor(header) format1 = QTextCharFormat() format1.setFontPointSize(16) cursor_header.insertHtml( "<p style='text-align: left;'><strong>Video</strong>: %s <strong> TimeStamp</strong>: %s </p>" % (videoName, timestamp)) cursor_header.insertHtml("<br><br><br> ") cursor_header.select(QTextCursor.Document) fragment_header = cursor_header.selection() document = QTextDocument() cursor = QTextCursor(document) tableFormat = QTextTableFormat() tableFormat.setHeaderRowCount(1) tableFormat.setBorderBrush(QBrush(Qt.black)) tableFormat.setAlignment(Qt.AlignHCenter) tableFormat.setCellPadding(5) tableFormat.setCellSpacing(5) cursor.movePosition(QTextCursor.Start, QTextCursor.MoveAnchor) cursor.insertFragment(fragment_header) textTable = cursor.insertTable(rows + 1, columns, tableFormat) tableHeaderFormat = QTextCharFormat() tableHeaderFormat.setBackground(QColor("#DADADA")) for column in range(columns): cell = textTable.cellAt(0, column) cell.setFormat(tableHeaderFormat) cellCursor = cell.firstCursorPosition() cellCursor.insertText( self.VManager.horizontalHeaderItem(column).data( Qt.DisplayRole)) for row in range(rows): for column in range(columns): item = self.VManager.item(row, column) if item is not None: cell = textTable.cellAt(row + 1, column) cellCursor = cell.firstCursorPosition() cellCursor.insertText( self.VManager.item(row, column).text()) cursor.movePosition(QTextCursor.End) printer.setOrientation(QPrinter.Portrait) printer.setPageMargins(30, 100, 10, 40, QPrinter.DevicePixel) printer.setFullPage(True) printer.setPageSize(QPrinter.A4) printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(fileName) document.print_(printer) QApplication.restoreOverrideCursor() qgsu.showUserAndLogMessage( QCoreApplication.translate("QgsFmvMetadata", "Succesfully creating PDF")) except Exception as e: QApplication.restoreOverrideCursor() qgsu.showUserAndLogMessage(QCoreApplication.translate( "QgsFmvMetadata", "Failed creating PDF"), level=QGis.Warning) return return
class widget1(QWidget): #widget def __init__(self, parent=None): super(widget1, self).__init__(parent) self.initUI() def initUI(self): #----------------------Widgets----------------------------- #Objeto document self.document=QTextDocument() #Qpusbutton button_data=QPushButton("Mostrar datos", self) button1=QPushButton("Vista Previa", self) button2=QPushButton("Imprimir", self) button3=QPushButton("Exportar", self) button4=QPushButton("Limpiar", self) #-------Objeto: QTreWidget------------------- self.table_user=QTreeWidget() self.table_user.setHeaderLabels(("Id_Usuario", "Mes", "Nombre", "Estatus", "Fecha de alta")) #Formato self.model=self.table_user.model() for indice, ancho in enumerate((110, 150, 150, 160), start=0): self.model.setHeaderData(indice, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole) self.table_user.setColumnWidth(indice, ancho) self.table_user.setAlternatingRowColors(True) #----------Objeto Layout vertical para QPushButton-------- horizontal_layout=QHBoxLayout() horizontal_layout.addWidget(button_data) horizontal_layout.addWidget(button1) horizontal_layout.addWidget(button2) horizontal_layout.addWidget(button3) horizontal_layout.addWidget(button4) horizontal_layout.addStretch() #---------Objeto - Layout----------------- gridLayout1=QGridLayout() #Agregar al gridlayout1 gridLayout1.addLayout(horizontal_layout, 0, 1, 1, 1) gridLayout1.addWidget(self.table_user, 1, 1, 1, 1)#widget #Asignar al layout clase widget self.setLayout(gridLayout1) #--------------Eventos qpushbutton---------------------------------------- button_data.clicked.connect(self.data) #data button1.clicked.connect(self.view) #var_view previa button2.clicked.connect(self.print_document) #imprimir button3.clicked.connect(self.pdf_export) #exportar button4.clicked.connect(self.clear) #limpiar def clear(self): #Limpiar tabla/documento self.table_user.clear() self.document.clear() def data (self): #Mostrar datos y objeto document data = [("1", "March", "Arnt", "Disabled", "10/23/2010"), ("2", "April", "Louis", "Enabled", "09/05/2020"), ("3", "June", "Steve", "Disabled", "02/15/2001"), ("4", "October", "Marcus", "Enabled", "01/13/2002"), ("5", "December", "John", "Enabled", "12/28/2018"), ] #Limpiar tabla/documento self.table_user.clear() self.document.clear() html_dato ='' item_widget=[] for d in data: #Imprimir datos en la tabla self.table_user.insertTopLevelItems(0,[QTreeWidgetItem(self.table_user, d)]) html_dato += "<tr> <td>%s</td> <td>%s</td> <td>%s</td> <td>%s</td> <td>%s</td> </tr>" %d item_widget.append(QTreeWidgetItem((str(d[0]), d[1], d[2], d[3], d[3]))) html=""" <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <style> h3 { font-family: Helvetica-Bold; text-align: center; } table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } td { text-align: left; padding-top: 4px; padding-right: 6px; padding-bottom: 2px; padding-left: 6px; } th { text-align: left; padding: 4px; background-color: black; color: white; } tr:nth-child(even) { background-color: #dddddd; } </style> </head> <body> <h3>LISTADO DE USUARIOS<br/></h3> <table align="left" width="100%" cellspacing="0"> <tr> <th>Id_Usuario</th> <th>Mes</th> <th>Nombre</th> <th>Estatus</th> <th>Fecha de alta</th> </tr> [DATA] </table> </body> </html> """.replace("[DATA]", html_dato) qbyte = QByteArray() qbyte.append(str(html)) #Ajuste codec = QTextCodec.codecForHtml(qbyte) unistr = codec.toUnicode(qbyte) if Qt.mightBeRichText(unistr): self.document.setHtml(unistr) else: self.document.setPlainText(unistr) def view(self): #Vista previa if not self.document.isEmpty(): impres = QPrinter(QPrinter.HighResolution) var_view = QPrintPreviewDialog(impres, self) var_view.setWindowTitle("Vista previa") var_view.setWindowFlags(Qt.Window) var_view.resize(800, 600) exportarPDF = var_view.findChildren(QToolBar) exportarPDF[0].addAction(QIcon("logo.png"), "Exportar a PDF", self.pdf_export) var_view.paintRequested.connect(self.visualizar) var_view.exec_() else: QMessageBox.critical(self, "Atención", "No hay datos en la tabla ", QMessageBox.Ok) def visualizar(self, imp): self.document.print_(imp) def pdf_export(self): if not self.document.isEmpty(): file1, _ = QFileDialog.getSaveFileName(self, "Exportar a PDF", "file", "Archivos PDF (*.pdf);;All Files (*)", options=QFileDialog.Options()) if file1: impres = QPrinter(QPrinter.HighResolution) impres.setOutputFormat(QPrinter.PdfFormat) impres.setOutputFileName(file1) self.document.print_(impres) QMessageBox.information(self, "Finalizado", "Se exportó correctamente el archivo", QMessageBox.Ok) else: QMessageBox.critical(self, "Atención", "No hay datos en la tabla", QMessageBox.Ok) def print_document(self): if not self.document.isEmpty(): impres = QPrinter(QPrinter.HighResolution) dlg = QPrintDialog(impres, self) dlg.setWindowTitle("Imprimir documento") if dlg.exec_() == QPrintDialog.Accepted: self.document.print_(impres) del dlg else: QMessageBox.critical(self, "Atención", "No hay datos en la tabla", QMessageBox.Ok)
class visualizarImprimirExportar(QDialog): def __init__(self, parent=None): super(visualizarImprimirExportar, self).__init__() self.setWindowTitle( "Visualizar, imprimir y exportar datos a PDF con PyQt5") self.setWindowIcon(QIcon("Qt.png")) self.setWindowFlags(Qt.WindowCloseButtonHint | Qt.MSWindowsFixedSizeDialogHint) self.setFixedSize(612, 408) self.initUI() def initUI(self): self.documento = QTextDocument() # =================== WIDGETS QPUSHBUTTON ================== buttonBuscar = QPushButton("Buscar usuarios", self) buttonBuscar.setFixedSize(426, 26) buttonBuscar.move(20, 20) buttonLimpiar = QPushButton("Limpiar tabla", self) buttonLimpiar.setFixedSize(140, 26) buttonLimpiar.move(452, 20) # =================== WIDGET QTREEWIDGET =================== self.treeWidgetUsuarios = QTreeWidget(self) self.treeWidgetUsuarios.setFont( QFont(self.treeWidgetUsuarios.font().family(), 10, False)) self.treeWidgetUsuarios.setRootIsDecorated(False) self.treeWidgetUsuarios.setHeaderLabels( ("D.N.I", "NOMBRE", "APELLIDO", "CORREO")) self.model = self.treeWidgetUsuarios.model() for indice, ancho in enumerate((110, 150, 150, 160), start=0): self.model.setHeaderData(indice, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole) self.treeWidgetUsuarios.setColumnWidth(indice, ancho) self.treeWidgetUsuarios.setAlternatingRowColors(True) self.treeWidgetUsuarios.setFixedSize(572, 300) self.treeWidgetUsuarios.move(20, 56) # =================== WIDGETS QPUSHBUTTON ================== buttonVistaPrevia = QPushButton("Vista previa", self) buttonVistaPrevia.setFixedSize(140, 26) buttonVistaPrevia.move(156, 364) buttonImprimir = QPushButton("Imprimir", self) buttonImprimir.setFixedSize(140, 26) buttonImprimir.move(304, 364) buttonExportarPDF = QPushButton("Exportar a PDF", self) buttonExportarPDF.setFixedSize(140, 26) buttonExportarPDF.move(452, 364) # =================== EVENTOS QPUSHBUTTON ================== buttonBuscar.clicked.connect(self.Buscar) buttonLimpiar.clicked.connect(self.limpiarTabla) buttonVistaPrevia.clicked.connect(self.vistaPrevia) buttonImprimir.clicked.connect(self.Imprimir) buttonExportarPDF.clicked.connect(self.exportarPDF) # ======================= FUNCIONES ============================ def Buscar(self): conexionDB = connect("Data/db_favan.db") cursor = conexionDB.cursor() cursor.execute( "SELECT ID_CLIENTE, NOM_CLIENTE, APE_CLIENTE, COR_CLIENTE FROM CLIENTE" ) datosDB = cursor.fetchall() conexionDB.close() if datosDB: self.documento.clear() self.treeWidgetUsuarios.clear() datos = "" item_widget = [] for dato in datosDB: datos += "<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>" % dato item_widget.append( QTreeWidgetItem((str(dato[0]), dato[1], dato[2], dato[3]))) reporteHtml = """ <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <style> h3 { font-family: Helvetica-Bold; text-align: center; } table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } td { text-align: left; padding-top: 4px; padding-right: 6px; padding-bottom: 2px; padding-left: 6px; } th { text-align: left; padding: 4px; background-color: purple; color: white; } tr:nth-child(even) { background-color: #dddddd; } </style> </head> <body> <h3>LISTADO DE USUARIOS<br/></h3> <table align="left" width="100%" cellspacing="0"> <tr> <th>D.N.I</th> <th>NOMBRE</th> <th>APELLIDO</th> <th>FECHA DE NACIMIENTO</th> </tr> [DATOS] </table> </body> </html> """.replace("[DATOS]", datos) datos = QByteArray() datos.append(str(reporteHtml)) codec = QTextCodec.codecForHtml(datos) unistr = codec.toUnicode(datos) if Qt.mightBeRichText(unistr): self.documento.setHtml(unistr) else: self.documento.setPlainText(unistr) self.treeWidgetUsuarios.addTopLevelItems(item_widget) else: QMessageBox.information(self, "Buscar usuarios", "No se encontraron resultados. ", QMessageBox.Ok) def limpiarTabla(self): self.documento.clear() self.treeWidgetUsuarios.clear() def vistaPrevia(self): if not self.documento.isEmpty(): impresion = QPrinter(QPrinter.HighResolution) vista = QPrintPreviewDialog(impresion, self) vista.setWindowTitle("Vista previa") vista.setWindowFlags(Qt.Window) vista.resize(800, 600) exportarPDF = vista.findChildren(QToolBar) exportarPDF[0].addAction(QIcon("exportarPDF.png"), "Exportar a PDF", self.exportarPDF) vista.paintRequested.connect(self.vistaPreviaImpresion) vista.exec_() else: QMessageBox.critical(self, "Vista previa", "No hay datos para visualizar. ", QMessageBox.Ok) def vistaPreviaImpresion(self, impresion): self.documento.print_(impresion) def Imprimir(self): if not self.documento.isEmpty(): impresion = QPrinter(QPrinter.HighResolution) dlg = QPrintDialog(impresion, self) dlg.setWindowTitle("Imprimir documento") if dlg.exec_() == QPrintDialog.Accepted: self.documento.print_(impresion) del dlg else: QMessageBox.critical(self, "Imprimir", "No hay datos para imprimir. ", QMessageBox.Ok) def exportarPDF(self): if not self.documento.isEmpty(): nombreArchivo, _ = QFileDialog.getSaveFileName( self, "Exportar a PDF", "Listado de usuarios", "Archivos PDF (*.pdf);;All Files (*)", options=QFileDialog.Options()) if nombreArchivo: # if QFileInfo(nombreArchivo).suffix(): # nombreArchivo += ".pdf" impresion = QPrinter(QPrinter.HighResolution) impresion.setOutputFormat(QPrinter.PdfFormat) impresion.setOutputFileName(nombreArchivo) self.documento.print_(impresion) QMessageBox.information(self, "Exportar a PDF", "Datos exportados con éxito. ", QMessageBox.Ok) else: QMessageBox.critical(self, "Exportar a PDF", "No hay datos para exportar. ", QMessageBox.Ok)
class visualizarImprimirExportar(QDialog): def __init__(self, parent=None): super(visualizarImprimirExportar, self).__init__() self.setWindowTitle("Просмотр, печать и экспорт данных в PDF") self.setWindowIcon(QIcon("Qt.png")) self.setWindowFlags(Qt.WindowCloseButtonHint | Qt.MSWindowsFixedSizeDialogHint) self.setFixedSize(612, 408) self.initUI() def initUI(self): self.documento = QTextDocument() buttonBuscar = QPushButton("Найти пользователей", self) buttonBuscar.setFixedSize(426, 26) buttonBuscar.move(20, 20) buttonLimpiar = QPushButton("Очистить", self) buttonLimpiar.setFixedSize(140, 26) buttonLimpiar.move(452, 20) self.treeWidgetUsuarios = QTreeWidget(self) self.treeWidgetUsuarios.setFont(QFont(self.treeWidgetUsuarios.font().family(), 10, False)) self.treeWidgetUsuarios.setRootIsDecorated(False) self.treeWidgetUsuarios.setHeaderLabels(("Id", "Имя", "Фамилия", "Пол", "Дата рождения", "Страна", "Телефон")) self.model = self.treeWidgetUsuarios.model() for indice, ancho in enumerate((110, 150, 150, 160), start=0): self.model.setHeaderData(indice, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole) self.treeWidgetUsuarios.setColumnWidth(indice, ancho) self.treeWidgetUsuarios.setAlternatingRowColors(True) self.treeWidgetUsuarios.setFixedSize(572, 300) self.treeWidgetUsuarios.move(20, 56) buttonVistaPrevia = QPushButton("предварительный просмотр", self) buttonVistaPrevia.setFixedSize(180, 26) buttonVistaPrevia.move(116, 364) buttonImprimir = QPushButton("печать", self) buttonImprimir.setFixedSize(140, 26) buttonImprimir.move(304, 364) buttonExportarPDF = QPushButton("Экспорт в PDF", self) buttonExportarPDF.setFixedSize(140, 26) buttonExportarPDF.move(452, 364) buttonBuscar.clicked.connect(self.Buscar) buttonLimpiar.clicked.connect(self.limpiarTabla) buttonVistaPrevia.clicked.connect(self.vistaPrevia) buttonImprimir.clicked.connect(self.Imprimir) buttonExportarPDF.clicked.connect(self.exportarPDF) def Buscar(self): conexionDB = connect("DB_SIACLE/DB_SIACLE.db") cursor = conexionDB.cursor() cursor.execute("SELECT NOMBRE, APELLIDO, SEXO, FECHA_NACIMIENTO, PAIS, TELEFONO_CELULAR FROM CLIENTES ") datosDB = cursor.fetchall() conexionDB.close() if datosDB: self.documento.clear() self.treeWidgetUsuarios.clear() datos = "" item_widget = [] for dato in datosDB: datos += "<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>" % dato item_widget.append(QTreeWidgetItem((str(dato[0]), dato[1], dato[2], dato[3], dato[4], dato[5]))) reporteHtml = """ <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <style> h3 { font-family: Helvetica-Bold; text-align: center; } table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } td { text-align: left; padding-top: 4px; padding-right: 6px; padding-bottom: 2px; padding-left: 6px; } th { text-align: left; padding: 4px; background-color: black; color: white; } tr:nth-child(even) { background-color: #dddddd; } </style> </head> <body> <h3>Клиенты<br/></h3> <table align="left" width="100%" cellspacing="0"> <tr> <th>Имя</th> <th>Фамилия</th> <th>Пол</th> <th>Дата рождения</th> <th>Страна</th> <th>Телефон</th> </tr> [DATOS] </table> </body> </html> """.replace("[DATOS]", datos) datos = QByteArray() datos.append(str(reporteHtml)) codec = QTextCodec.codecForHtml(datos) unistr = codec.toUnicode(datos) if Qt.mightBeRichText(unistr): self.documento.setHtml(unistr) else: self.documento.setPlainText(unistr) self.treeWidgetUsuarios.addTopLevelItems(item_widget) else: QMessageBox.information(self, "Найти пользователей", "Результатов не найдено. ", QMessageBox.Ok) def limpiarTabla(self): self.documento.clear() self.treeWidgetUsuarios.clear() def vistaPrevia(self): if not self.documento.isEmpty(): impresion = QPrinter(QPrinter.HighResolution) vista = QPrintPreviewDialog(impresion, self) vista.setWindowTitle("предварительный просмотр") vista.setWindowFlags(Qt.Window) vista.resize(800, 600) exportarPDF = vista.findChildren(QToolBar) exportarPDF[0].addAction(QIcon("exportarPDF.png"), "Экспорт в PDF", self.exportarPDF) vista.paintRequested.connect(self.vistaPreviaImpresion) vista.exec_() else: QMessageBox.critical(self, "предварительный просмотр", "Нет данных для отображения. ", QMessageBox.Ok) def vistaPreviaImpresion(self, impresion): self.documento.print_(impresion) def Imprimir(self): if not self.documento.isEmpty(): impresion = QPrinter(QPrinter.HighResolution) dlg = QPrintDialog(impresion, self) dlg.setWindowTitle("Распечатать документ") if dlg.exec_() == QPrintDialog.Accepted: self.documento.print_(impresion) del dlg else: QMessageBox.critical(self, "печать", "Нет данных для печати. ", QMessageBox.Ok) def exportarPDF(self): if not self.documento.isEmpty(): nombreArchivo, _ = QFileDialog.getSaveFileName(self, "Экспорт в PDF", "Список пользователей ", "PDF файлы (*.doc);;All Files (*)", options=QFileDialog.Options()) if nombreArchivo: impresion = QPrinter(QPrinter.HighResolution) impresion.setOutputFormat(QPrinter.PdfFormat) impresion.setOutputFileName(nombreArchivo) self.documento.print_(impresion) QMessageBox.information(self, "Экспорт в PDF", "Данные успешно экспортированы. ", QMessageBox.Ok) else: QMessageBox.critical(self, "Экспорт в PDF", "Нет данных для экспорта. ", QMessageBox.Ok)
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 align=center>" # "Transactions1</td></tr>") # for date, amount in statement.transactions: # color, status = "black", "Credit" # if amount < 0: # color, status = "red", "Debit" # htmltext += ("<tr><td align=right width=200>{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>") htmltext = "<p>美莱项目组欢迎您!</p>" dialog = QPrintDialog(self.printer, self) if dialog.exec_(): #printer # print(self.printer.logicalDpiX()) # print(self.printer.logicalDpiX() * (257 / 25.4)) # print(self.printer.logicalDpiY()) # print(self.printer.logicalDpiY() * (125 / 25.4)) qsizeF = QSizeF(self.printer.logicalDpiX() * (257 / 25.4), self.printer.logicalDpiY() * (125 / 25.4)) # qsizeF = QSizeF(self.printer.logicalDpiX() * (210 / 25.4), self.printer.logicalDpiY() * (297 / 25.4)); self.printer.setPageSize(QPrinter.Custom) self.printer.setPaperName("小票2") paperSize = QSizeF(257, 125) self.printer.setPaperSize(paperSize, QPrinter.Millimeter) # self.printer.setPageSizeMM(qsizeF) # self.printer.setFullPage(True); # self.printer.setOrientation(QPrinter.Portrait); # self.printer.setOutputFormat(QPrinter.NativeFormat) # document document = QTextDocument() document.setPageSize(qsizeF) font = QFont() font.setPointSize(6) document.setDefaultFont(font) 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)