def doPrint(self): printer = QPrinter() dlg = QPrintDialog(printer, self) dlg.setWindowTitle('Печать документа') if dlg.exec() == QPrintDialog.Accepted: self.ui.textBrowser.print(printer) self.close()
def print_webpage(self): """Print the webpage to a printer. Callback for the print action. Should show a print dialog and print the webpage to the printer. """ if self.print_settings.get("mode") == "high": printer = QPrinter(mode=QPrinter.HighResolution) else: printer = QPrinter(mode=QPrinter.ScreenResolution) if self.print_settings: if self.print_settings.get("size_unit"): try: unit = getattr( QPrinter, self.print_settings.get("size_unit").capitalize() ) except NameError: debug( "Specified print size unit '{}' not found," "using default.".format( self.print_settings.get("size_unit") )) unit = QPrinter.Millimeter else: unit = QPrinter.Millimeter margins = ( list(self.print_settings.get("margins")) or list(printer.getPageMargins(unit)) ) margins += [unit] printer.setPageMargins(*margins) if self.print_settings.get("orientation") == "landscape": printer.setOrientation(QPrinter.Landscape) else: printer.setOrientation(QPrinter.Portrait) if self.print_settings.get("paper_size"): printer.setPaperSize(QSizeF( *self.print_settings.get("paper_size") ), unit) if self.print_settings.get("resolution"): printer.setResolution( int(self.print_settings.get("resolution")) ) if not self.print_settings.get("silent"): print_dialog = QPrintDialog(printer, self) print_dialog.setWindowTitle("Print Page") if not print_dialog.exec_() == QDialog.Accepted: return False self.print_(printer) return True
def printFile(self): title, htmltext, preview = self.currentTab.getDocumentForExport() printer = self.standardPrinter(title) dlg = QPrintDialog(printer, self) dlg.setWindowTitle(self.tr("Print document")) if (dlg.exec() == QDialog.Accepted): document = self.getDocumentForPrint(title, htmltext, preview) if document != None: document.print(printer)
def printFile(self): self.currentTab.updatePreviewBox() printer = self.standardPrinter() dlg = QPrintDialog(printer, self) dlg.setWindowTitle(self.tr("Print document")) if (dlg.exec() == QDialog.Accepted): document = self.getDocumentForPrint() if document != None: document.print(printer)
def printFile(self): self.updatePreviewBox() printer = self.standardPrinter() dlg = QPrintDialog(printer, self) dlg.setWindowTitle(self.tr("Print document")) if (dlg.exec() == QDialog.Accepted): document = self.getDocumentForPrint() if document != None: document.print(printer)
def printFile(self): title, htmltext, preview = self.currentTab.getDocumentForExport(includeStyleSheet=True, webenv=False) printer = self.standardPrinter(title) dlg = QPrintDialog(printer, self) dlg.setWindowTitle(self.tr("Print document")) if (dlg.exec() == QDialog.Accepted): document = self.getDocumentForPrint(title, htmltext, preview) if document != None: document.print(printer)
def print(self, printer=None, pageNumbers=None, showDialog=True): """Print the contents of the View.""" import qpageview.poppler import qpageview.cupsprinter if printer is None: if self._printer is None: self._printer = QPrinter() printer = self._printer printer.setCopyCount(1) # prevent embarrassing situations :-) if self.document() and self.document().filename(): filename = os.path.basename(self.document().filename()) else: filename = "" printer.setDocName(filename) if showDialog: qpageview.cupsprinter.clearPageSetSetting(printer) dlg = QPrintDialog(printer, self) if filename: title = app.caption( _("Print {filename}").format(filename=filename)) else: title = app.caption(_("Print")) dlg.setWindowTitle(title) dlg.setMinMax(1, self.pageCount()) if not dlg.exec_(): return # cancelled s = QSettings() printer.setResolution(s.value("printing/dpi", 300, int)) # is it possible and preferred to print a PDF directly with cups? # on Mac, when printing directly with cups, the system print window is shown # but its settings are ignored and any choice (including opening the PDF) # results in printing to cups' default printer if (s.value("printing/directcups", False if sys.platform.startswith('darwin') else True, bool) and isinstance(self.document(), qpageview.poppler.PopplerDocument) and os.path.isfile(self.document().filename()) and not printer.outputFileName()): h = qpageview.cupsprinter.handle(printer) if h: if not h.printFile(self.document().filename()): QMessageBox.warning( self, _("Printing Error"), "{0}\n{1}".format( _("An error occurred (code: {num}):").format( num=h.status), h.error)) return job = super().print(printer, pageNumbers, False) if job: progress = PrintProgressDialog(job, self) progress.setWindowTitle(title) progress.setLabelText(_("Preparing to print...")) progress.show()
def print_(self): printer = QPrinter() dlg = QPrintDialog(printer, self) dlg.setWindowTitle(app.caption(_("Print"))) options = (QAbstractPrintDialog.PrintToFile | QAbstractPrintDialog.PrintShowPageSize | QAbstractPrintDialog.PrintPageRange) if self.browser.textCursor().hasSelection(): options |= QAbstractPrintDialog.PrintSelection dlg.setOptions(options) if dlg.exec_(): self.browser.print_(printer)
def printFile(self): editor = self.solvers.currentWidget() if type(editor) == QTextEdit: printer = QPrinter() dialog = QPrintDialog(printer, self) dialog.setWindowTitle("Print Document") if dialog.exec_() != QDialog.Accepted: return editor.print_(printer) else: answer = QMessageBox.warning(self, "Not Print Image", "Dont print graph.", QMessageBox.Ok)
def filePrint(self): printer = QPrinter(QPrinter.HighResolution) dlg = QPrintDialog(printer, self) if self.textEdit.textCursor().hasSelection(): dlg.addEnabledOption(QPrintDialog.PrintSelection) dlg.setWindowTitle("Print Document") if dlg.exec_() == QPrintDialog.Accepted: self.textEdit.print_(printer) del dlg
def print(self): print("controller.print") editor = self.ui.webView printer = QPrinter() #print(printer, self) dialog = QPrintDialog(printer, self) dialog.setWindowTitle("Print Document") if dialog.exec_() != QDialog.Accepted: return editor.print_(printer)
def filePrint(self): printer = QPrinter(QPrinter.HighResolution) dlg = QPrintDialog(printer, self) if self.textEdit.textCursor().hasSelection(): dlg.addEnabledOption(QPrintDialog.PrintSelection) dlg.setWindowTitle("Print Document") if dlg.exec_() == QPrintDialog.Accepted: self.textEdit.print_(printer) del dlg
def print_webpage(self): """Print the webpage to a printer. Callback for the print action. Should show a print dialog and print the webpage to the printer. """ if self.print_settings.get("mode") == "high": printer = QPrinter(mode=QPrinter.HighResolution) else: printer = QPrinter(mode=QPrinter.ScreenResolution) if self.print_settings: if self.print_settings.get("size_unit"): try: unit = getattr( QPrinter, self.print_settings.get("size_unit").capitalize()) except NameError: debug("Specified print size unit '{}' not found," "using default.".format( self.print_settings.get("size_unit"))) unit = QPrinter.Millimeter else: unit = QPrinter.Millimeter margins = (list(self.print_settings.get("margins")) or list(printer.getPageMargins(unit))) margins += [unit] printer.setPageMargins(*margins) if self.print_settings.get("orientation") == "landscape": printer.setOrientation(QPrinter.Landscape) else: printer.setOrientation(QPrinter.Portrait) if self.print_settings.get("paper_size"): printer.setPaperSize( QSizeF(*self.print_settings.get("paper_size")), unit) if self.print_settings.get("resolution"): printer.setResolution( int(self.print_settings.get("resolution"))) if not self.print_settings.get("silent"): print_dialog = QPrintDialog(printer, self) print_dialog.setWindowTitle("Print Page") if not print_dialog.exec_() == QDialog.Accepted: return False self.print_(printer) return True
def printFile(self): editor = self.letters.currentWidget() printer = QPrinter() dialog = QPrintDialog(printer, self) dialog.setWindowTitle("Print Document") if editor.textCursor().hasSelection(): dialog.addEnabledOption(QAbstractPrintDialog.PrintSelection) if dialog.exec_() != QDialog.Accepted: return editor.print_(printer)
def printFile(self): editor = self.letters.currentWidget() printer = QPrinter() dialog = QPrintDialog(printer, self) dialog.setWindowTitle("Print Document") if editor.textCursor().hasSelection(): dialog.addEnabledOption(QAbstractPrintDialog.PrintSelection) if dialog.exec_() != QDialog.Accepted: return editor.print_(printer)
def printFile(self): editor = self.solvers.currentWidget() if type(editor) == QTextEdit: printer = QPrinter() dialog = QPrintDialog(printer, self) dialog.setWindowTitle("Print Document") if dialog.exec_() != QDialog.Accepted: return editor.print_(printer) else: answer = QMessageBox.warning(self, "Not Print Image", "Dont print graph.", QMessageBox.Ok)
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 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)
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 onPrint(self): doc = QsciPrinter() dialog = QPrintDialog(doc, self) dialog.setWindowTitle('Print') if (dialog.exec_() == QDialog.Accepted): self.textPad.setPythonPrintStyle() try: doc.printRange(self.textPad) except Exception as e: print(str(e)) else: return self.textPad.setPythonStyle()
def printSource(self): cursor = self.textCursor() try: printer = self._sourcePrinter except AttributeError: printer = self._sourcePrinter = QPrinter() else: printer.setCopyCount(1) dlg = QPrintDialog(printer, self) dlg.setWindowTitle(app.caption(_("dialog title", "Print Source"))) options = QAbstractPrintDialog.PrintToFile | QAbstractPrintDialog.PrintShowPageSize if cursor.hasSelection(): options |= QAbstractPrintDialog.PrintSelection dlg.setOptions(options) if dlg.exec_(): if dlg.printRange() != QAbstractPrintDialog.Selection: cursor.clearSelection() number_lines = QSettings().value("source_export/number_lines", False, bool) doc = highlighter.html_copy(cursor, 'printer', number_lines) doc.setMetaInformation(QTextDocument.DocumentTitle, self.currentDocument().url().toString()) font = doc.defaultFont() font.setPointSizeF(font.pointSizeF() * 0.8) doc.setDefaultFont(font) doc.print_(printer)
def printSource(self): cursor = self.textCursor() try: printer = self._sourcePrinter except AttributeError: printer = self._sourcePrinter = QPrinter() else: printer.setCopyCount(1) dlg = QPrintDialog(printer, self) dlg.setWindowTitle(app.caption(_("dialog title", "Print Source"))) options = QAbstractPrintDialog.PrintToFile | QAbstractPrintDialog.PrintShowPageSize if cursor.hasSelection(): options |= QAbstractPrintDialog.PrintSelection dlg.setOptions(options) if dlg.exec_(): if dlg.printRange() != QAbstractPrintDialog.Selection: cursor.clearSelection() number_lines = QSettings().value("source_export/number_lines", False, bool) doc = highlighter.html_copy(cursor, 'printer', number_lines) doc.setMetaInformation(QTextDocument.DocumentTitle, self.currentDocument().url().toString()) font = doc.defaultFont() font.setPointSizeF(font.pointSizeF() * 0.8) doc.setDefaultFont(font) doc.print_(printer)
def print_(self, method): """ Print the contents of the ConsoleWidget to the specified QPrinter.""" self.receipt_other.append( datetime.datetime.now().strftime("%m%d%y%H%M%S")) self.receipt_other.append( datetime.datetime.now().strftime("%m/%d/%Y %H:%M:%S")) self.receipt_other.append(self.employee_id_lbl.text()) self.receipt_other.append(method) self.receipt_other.append( str(Decimal(self.subtotal).quantize(self.cents, ROUND_HALF_UP))) self.receipt_other.append( str(Decimal(self.tax).quantize(self.cents, ROUND_HALF_UP))) self.receipt_other.append( str(Decimal(self.total).quantize(self.cents, ROUND_HALF_UP))) self.receipt_date = datetime.datetime.now().strftime("%m/%d/%Y") print(str(self.receipt_date)) header = "Smith's Grocery\n\n123 ABC Lane\nLogan,UT 84321\n555-435-1234\n\n{}\nCashier: {}\nPayment Method: {}\nReceipt ID: {}\n\n_______________________________\n".format( self.receipt_other[1], self.receipt_other[2], self.receipt_other[3], self.receipt_other[0]) footer = "_______________________________\nSubtotal: {}\nTax: {}\n\nTotal: {}".format( self.bc_r_subtotal_lbl.text(), self.bc_tax_lbl.text(), self.bc_total_lbl.text()) receipt = "" receipt += header for i in range(0, len(self.receipt_names)): if isinstance(self.receipt_quantity[i], int): receipt += (self.receipt_text[i] + ' (' + str(self.receipt_quantity[i]) + ')' + '\n$' + str( int(self.receipt_quantity[i]) * float(self.receipt_price[i])) + '\n\n') else: receipt += (self.receipt_text[i] + ' (' + str(self.receipt_quantity[i]) + ' lbs)' + '\n$' + str( Decimal( float(self.receipt_quantity[i]) * float(self.receipt_price[i])).quantize( self.cents, ROUND_HALF_UP)) + '\n\n') receipt += footer # Appli = QApplication(sys.argv) printer = QPrinter() doc = QTextDocument(receipt) dialog = QPrintDialog(printer) dialog.setModal(True) dialog.setWindowTitle("Print Receipt") print("Names: " + str(self.receipt_names)) print("Prices: " + str(self.receipt_price)) print("Names: " + str(self.receipt_quantity)) print("Text: " + str(self.receipt_text)) print("Other: " + str(self.receipt_other)) # dialog.addEnabledOption(QAbstractPrintDialog.PrintSelection) if dialog.exec_() == True: try: doc.print_(printer) except: print("?") self.receipts_table = self.db['receipts'] self.receipts_table.insert( dict(date=str(self.receipt_date), other=str(self.receipt_other), name=str(self.receipt_names), quantity=str(self.receipt_quantity), price=str(self.receipt_price), text=str(self.receipt_text), r_id=self.receipt_other[0])) self.update_inventory() self.populate_mo_listview() self.cancel_transaction()
def slotPrint(self): printer = QPrinter() dlg = QPrintDialog(printer, self) dlg.setWindowTitle(app.caption(_("Print"))) if dlg.exec_(): self.webview.print_(printer)
def print_(doc, filename=None, widget=None): """Prints the popplerqt5.Poppler.Document. The filename is used in the dialog and print job name. If the filename is not given, it defaults to a translation of "PDF Document". The widget is a widget to use as parent for the print dialog etc. """ # Decide how we will print. # on Windows and Mac OS X a print command must be specified, otherwise # we'll use raster printing s = QSettings() s.beginGroup("helper_applications") cmd = s.value("printcommand", "", str) use_dialog = s.value("printcommand/dialog", False, bool) resolution = s.value("printcommand/dpi", 300, int) linux_lpr = False if os.name != 'nt' and not sys.platform.startswith('darwin'): # we're probably on Linux if not cmd: cmd = fileprinter.lprCommand() if cmd: linux_lpr = True elif cmd.split('/')[-1] in fileprinter.lpr_commands: linux_lpr = True print_file = filename title = os.path.basename(filename) if filename else _("PDF Document") if widget: try: printer = _printers[widget] except KeyError: printer = _printers[widget] = QPrinter() else: printer.setCopyCount(1) else: printer = QPrinter() printer.setDocName(title) printer.setPrintRange(QPrinter.AllPages) if linux_lpr or use_dialog or not cmd: dlg = QPrintDialog(printer, widget) dlg.setMinMax(1, doc.numPages()) dlg.setOption(QPrintDialog.PrintToFile, False) dlg.setWindowTitle( app.caption(_("Print {filename}").format(filename=title))) result = dlg.exec_() if widget: dlg.deleteLater() # because it has a parent if not result: return # cancelled if linux_lpr or '$ps' in cmd: # make a PostScript file with the desired paper size ps = QTemporaryFile() if ps.open() and qpopplerview.printer.psfile(doc, printer, ps): ps.close() print_file = ps.fileName() elif cmd: if printer.printRange() != QPrinter.AllPages: cmd = None # we can't cut out pages from a PDF file elif '$pdf' not in cmd: cmd += ' $pdf' command = [] if linux_lpr: # let all converted pages print printer.setPrintRange(QPrinter.AllPages) command = fileprinter.printCommand(cmd, printer, ps.fileName()) elif cmd and print_file: for arg in helpers.shell_split(cmd): if arg in ('$ps', '$pdf'): command.append(print_file) else: arg = arg.replace('$printer', printer.printerName()) command.append(arg) if command: if subprocess.call(command): QMessageBox.warning( widget, _("Printing Error"), _("Could not send the document to the printer.")) return else: # Fall back printing of rendered raster images. # It is unsure if the Poppler ArthurBackend ever will be ready for # good rendering directly to a painter, so we'll fall back to using # raster images. p = Printer() p.setDocument(doc) p.setPrinter(printer) p.setResolution(resolution) d = QProgressDialog() d.setModal(True) d.setMinimumDuration(0) d.setRange(0, len(p.pageList()) + 1) d.canceled.connect(p.abort) def progress(num, total, page): d.setValue(num) d.setLabelText( _("Printing page {page} ({num} of {total})...").format( page=page, num=num, total=total)) def finished(): p.deleteLater() d.deleteLater() d.hide() if not p.success and not p.aborted(): QMessageBox.warning( widget, _("Printing Error"), _("Could not send the document to the printer.")) p.finished.connect(finished) p.printing.connect(progress) p.start()
def print_(doc, filename=None, widget=None): """Prints the popplerqt5.Poppler.Document. The filename is used in the dialog and print job name. If the filename is not given, it defaults to a translation of "PDF Document". The widget is a widget to use as parent for the print dialog etc. """ # Decide how we will print. # on Windows and Mac OS X a print command must be specified, otherwise # we'll use raster printing s = QSettings() s.beginGroup("helper_applications") cmd = s.value("printcommand", "", str) use_dialog = s.value("printcommand/dialog", False, bool) resolution = s.value("printcommand/dpi", 300, int) linux_lpr = False if os.name != 'nt' and not sys.platform.startswith('darwin'): # we're probably on Linux if not cmd: cmd = fileprinter.lprCommand() if cmd: linux_lpr = True elif cmd.split('/')[-1] in fileprinter.lpr_commands: linux_lpr = True print_file = filename title = os.path.basename(filename) if filename else _("PDF Document") if widget: try: printer = _printers[widget] except KeyError: printer = _printers[widget] = QPrinter() else: printer.setCopyCount(1) else: printer = QPrinter() printer.setDocName(title) printer.setPrintRange(QPrinter.AllPages) if linux_lpr or use_dialog or not cmd: dlg = QPrintDialog(printer, widget) dlg.setMinMax(1, doc.numPages()) dlg.setOption(QPrintDialog.PrintToFile, False) dlg.setWindowTitle(app.caption(_("Print {filename}").format(filename=title))) result = dlg.exec_() if widget: dlg.deleteLater() # because it has a parent if not result: return # cancelled if linux_lpr or '$ps' in cmd: # make a PostScript file with the desired paper size ps = QTemporaryFile() if ps.open() and qpopplerview.printer.psfile(doc, printer, ps): ps.close() print_file = ps.fileName() elif cmd: if printer.printRange() != QPrinter.AllPages: cmd = None # we can't cut out pages from a PDF file elif '$pdf' not in cmd: cmd += ' $pdf' command = [] if linux_lpr: # let all converted pages print printer.setPrintRange(QPrinter.AllPages) command = fileprinter.printCommand(cmd, printer, ps.fileName()) elif cmd and print_file: for arg in helpers.shell_split(cmd): if arg in ('$ps', '$pdf'): command.append(print_file) else: arg = arg.replace('$printer', printer.printerName()) command.append(arg) if command: if subprocess.call(command): QMessageBox.warning(widget, _("Printing Error"), _("Could not send the document to the printer.")) return else: # Fall back printing of rendered raster images. # It is unsure if the Poppler ArthurBackend ever will be ready for # good rendering directly to a painter, so we'll fall back to using # raster images. p = Printer() p.setDocument(doc) p.setPrinter(printer) p.setResolution(resolution) d = QProgressDialog() d.setModal(True) d.setMinimumDuration(0) d.setRange(0, len(p.pageList()) + 1) d.canceled.connect(p.abort) def progress(num, total, page): d.setValue(num) d.setLabelText(_("Printing page {page} ({num} of {total})...").format( page=page, num=num, total=total)) def finished(): p.deleteLater() d.deleteLater() d.hide() if not p.success and not p.aborted(): QMessageBox.warning(widget, _("Printing Error"), _("Could not send the document to the printer.")) p.finished.connect(finished) p.printing.connect(progress) p.start()
def printImage(self): if self.model.rowCount(QModelIndex()) * self.model.columnCount( QModelIndex()) > 90000: answer = QMessageBox.question( self, "Large Image Size", "The printed image may be very large. Are you sure that " "you want to print it?", QMessageBox.Yes | QMessageBox.No) if answer == QMessageBox.No: return printer = QPrinter(QPrinter.HighResolution) dlg = QPrintDialog(printer, self) dlg.setWindowTitle("Print Image") if dlg.exec_() != QDialog.Accepted: return painter = QPainter() painter.begin(printer) rows = self.model.rowCount(QModelIndex()) columns = self.model.columnCount(QModelIndex()) sourceWidth = (columns + 1) * ItemSize sourceHeight = (rows + 1) * ItemSize painter.save() xscale = printer.pageRect().width() / float(sourceWidth) yscale = printer.pageRect().height() / float(sourceHeight) scale = min(xscale, yscale) painter.translate( printer.paperRect().x() + printer.pageRect().width() / 2, printer.paperRect().y() + printer.pageRect().height() / 2) painter.scale(scale, scale) painter.translate(-sourceWidth / 2, -sourceHeight / 2) option = QStyleOptionViewItem() parent = QModelIndex() progress = QProgressDialog("Printing...", "Cancel", 0, rows, self) progress.setWindowModality(Qt.ApplicationModal) y = ItemSize / 2.0 for row in range(rows): progress.setValue(row) QApplication.processEvents() if progress.wasCanceled(): break x = ItemSize / 2.0 for column in range(columns): option.rect = QRect(x, y, ItemSize, ItemSize) self.view.itemDelegate().paint( painter, option, self.model.index(row, column, parent)) x += ItemSize y += ItemSize progress.setValue(rows) painter.restore() painter.end() if progress.wasCanceled(): QMessageBox.information(self, "Printing canceled", "The printing process was canceled.", QMessageBox.Cancel)
def print_webpage(self): """Print the webpage to a printer. Callback for the print action. Should show a print dialog and print the webpage to the printer. """ print_settings = self.config.get("print_settings", {}) if print_settings.get("mode") == "high": printer = QPrinter(mode=QPrinter.HighResolution) else: printer = QPrinter(mode=QPrinter.ScreenResolution) # set which printer # FIXME: This isn't documented, because it doesn't seem to work... if print_settings.get("printer_name"): debug( "Setting printer to: {}".format( print_settings.get("printer_name")) ) printer.setPrinterName(print_settings.get("printer_name")) debug("Printer is now: {}".format(printer.printerName())) # Set the units unit_name = print_settings.get("size_unit", 'Millimeter').title() try: unit = getattr(QPrinter, unit_name) except AttributeError: debug( "Specified print size unit '{}' not found, using default." .format(unit_name) ) unit = QPrinter.Millimeter # Set the margins margins = list( print_settings.get("margins", printer.getPageMargins(unit)) ) margins.append(unit) printer.setPageMargins(*margins) # Set the Orientation orientation = print_settings.get("orientation", 'Portrait').title() printer.setOrientation( getattr(QPrinter, orientation, QPrinter.Portrait) ) # Set the paper size paper_size = print_settings.get("paper_size") if type(paper_size) in (list, tuple): # Assume it's a width/height spec printer.setPaperSize(QSizeF(*paper_size), unit) elif paper_size is not None: # Assume it's a size name printer.setPaperSize(getattr(QPrinter, paper_size, 'AnsiA')) # If paper_size is None, we just leave it at the printer's default # Set the resolution resolution = print_settings.get("resolution") if resolution: printer.setResolution(int(resolution)) # Show a print dialog, unless we want silent printing if not print_settings.get("silent"): print_dialog = QPrintDialog(printer, self) print_dialog.setWindowTitle("Print Page") if not print_dialog.exec_() == QDialog.Accepted: return False self.print_(printer) return True
def printImage(self): if self.model.rowCount(QModelIndex()) * self.model.columnCount(QModelIndex()) > 90000: answer = QMessageBox.question(self, "Large Image Size", "The printed image may be very large. Are you sure that " "you want to print it?", QMessageBox.Yes | QMessageBox.No) if answer == QMessageBox.No: return printer = QPrinter(QPrinter.HighResolution) dlg = QPrintDialog(printer, self) dlg.setWindowTitle("Print Image") if dlg.exec_() != QDialog.Accepted: return painter = QPainter() painter.begin(printer) rows = self.model.rowCount(QModelIndex()) columns = self.model.columnCount(QModelIndex()) sourceWidth = (columns+1) * ItemSize sourceHeight = (rows+1) * ItemSize painter.save() xscale = printer.pageRect().width() / float(sourceWidth) yscale = printer.pageRect().height() / float(sourceHeight) scale = min(xscale, yscale) painter.translate(printer.paperRect().x()+printer.pageRect().width()/2, printer.paperRect().y()+printer.pageRect().height()/2) painter.scale(scale, scale) painter.translate(-sourceWidth/2, -sourceHeight/2) option = QStyleOptionViewItem() parent = QModelIndex() progress = QProgressDialog("Printing...", "Cancel", 0, rows, self) progress.setWindowModality(Qt.ApplicationModal) y = ItemSize / 2.0 for row in range(rows): progress.setValue(row) QApplication.processEvents() if progress.wasCanceled(): break x = ItemSize / 2.0 for column in range(columns): option.rect = QRect(x, y, ItemSize, ItemSize) self.view.itemDelegate().paint(painter, option, self.model.index(row, column, parent)) x += ItemSize y += ItemSize progress.setValue(rows) painter.restore() painter.end() if progress.wasCanceled(): QMessageBox.information(self, "Printing canceled", "The printing process was canceled.", QMessageBox.Cancel)
def print_webpage(self): """Print the webpage to a printer. Callback for the print action. Should show a print dialog and print the webpage to the printer. """ print_settings = self.config.get("print_settings", {}) if print_settings.get("mode") == "high": printer = QPrinter(mode=QPrinter.HighResolution) else: printer = QPrinter(mode=QPrinter.ScreenResolution) # set which printer # FIXME: This isn't documented, because it doesn't seem to work... if print_settings.get("printer_name"): debug("Setting printer to: {}".format( print_settings.get("printer_name"))) printer.setPrinterName(print_settings.get("printer_name")) debug("Printer is now: {}".format(printer.printerName())) # Set the units unit_name = print_settings.get("size_unit", 'Millimeter').title() try: unit = getattr(QPrinter, unit_name) except AttributeError: debug("Specified print size unit '{}' not found, using default.". format(unit_name)) unit = QPrinter.Millimeter # Set the margins margins = list( print_settings.get("margins", printer.getPageMargins(unit))) margins.append(unit) printer.setPageMargins(*margins) # Set the Orientation orientation = print_settings.get("orientation", 'Portrait').title() printer.setOrientation( getattr(QPrinter, orientation, QPrinter.Portrait)) # Set the paper size paper_size = print_settings.get("paper_size") if type(paper_size) in (list, tuple): # Assume it's a width/height spec printer.setPaperSize(QSizeF(*paper_size), unit) elif paper_size is not None: # Assume it's a size name printer.setPaperSize(getattr(QPrinter, paper_size, 'AnsiA')) # If paper_size is None, we just leave it at the printer's default # Set the resolution resolution = print_settings.get("resolution") if resolution: printer.setResolution(int(resolution)) # Show a print dialog, unless we want silent printing if not print_settings.get("silent"): print_dialog = QPrintDialog(printer, self) print_dialog.setWindowTitle("Print Page") if not print_dialog.exec_() == QDialog.Accepted: return False self.print_(printer) return True
def slotPrint(self): printer = QPrinter() dlg = QPrintDialog(printer, self) dlg.setWindowTitle(app.caption(_("Print"))) if dlg.exec_(): self.webview.print_(printer)
class ReportEditor(QMainWindow, Ui_ReportEditorWindow): def __init__(self, processor, parent=None): super().__init__(parent) self.processor = processor self.settings = SupremeSettings() self._report_items = {} self._file_name = None self.setupUi(self) self.splitter.setStretchFactor(0, 1) self.splitter.setStretchFactor(1, 3) self.actionUpdate.triggered.connect(self._create_report) self.usedList.doubleClicked.connect( lambda i: self.usedList.takeItem(i.row())) self._setup_text_editor() self._setup_text_connections() self._init_report_items() def _init_report_items(self): items = [report_class(self.processor, parent=self.availableList) for report_class in _report_classes] factory = AlgorithmReportFactory(self.processor, self.availableList) items += factory.get_report_items() self._report_items = {} for report_item in items: self._report_items[report_item.name] = report_item self.availableList.addItem(report_item) self.availableList.mousePressEvent = self._av_list_mouse_press_event def _av_list_mouse_press_event(self, event: QMouseEvent): if event.button() == Qt.RightButton: item = self.availableList.itemAt(event.pos()) if hasattr(item, 'settings'): item.change_settings() QListWidget.mousePressEvent(self.availableList, event) def _create_report(self): self.textEdit.clear() self.statusbar.showMessage('Создание отчёта...') html = "" for i in range(self.usedList.count()): list_item = self.usedList.item(i) report_item = self._report_items[list_item.text()] html += report_item.create_html() html = encapsulate_html(html) self.textEdit.setHtml(html) self.textEdit.document().setModified(True) self.statusbar.showMessage('Отчёт создан') def _setup_text_editor(self): self.styleComboBox = QComboBox(self.fontToolBar) self.styleComboBox.addItem("Standard") self.styleComboBox.addItem("Bullet List (Disc)") self.styleComboBox.addItem("Bullet List (Circle)") self.styleComboBox.addItem("Bullet List (Square)") self.styleComboBox.addItem("Ordered List (Decimal)") self.styleComboBox.addItem("Ordered List (Alpha lower)") self.styleComboBox.addItem("Ordered List (Alpha upper)") self.styleComboBox.addItem("Ordered List (Roman lower)") self.styleComboBox.addItem("Ordered List (Roman upper)") self.styleComboBox.addItem("Heading 1") self.styleComboBox.addItem("Heading 2") self.styleComboBox.addItem("Heading 3") self.styleComboBox.addItem("Heading 4") self.styleComboBox.addItem("Heading 5") self.styleComboBox.addItem("Heading 6") self.fontToolBar.addWidget(self.styleComboBox) self.fontComboBox = QFontComboBox(self.fontToolBar) # TODO connect self.fontToolBar.addWidget(self.fontComboBox) self.sizeComboBox = QComboBox(self.fontToolBar) # TODO connect sizes = QFontDatabase.standardSizes() [self.sizeComboBox.addItem(str(size)) for size in sizes] self.sizeComboBox.setCurrentIndex( sizes.index(QApplication.font().pointSize())) self.fontToolBar.addWidget(self.sizeComboBox) def _setup_text_connections(self): self.textEdit.currentCharFormatChanged.connect( self._current_char_format_changed) self.textEdit.cursorPositionChanged.connect( self._cursor_position_changed) self.actionSave.triggered.connect(self._save) self.actionSaveAs.triggered.connect(self._save_as) self.actionBrowser.triggered.connect(self._browser) self.actionPrint.triggered.connect(self._print) self.actionPrintPreview.triggered.connect(self._print_preview) self.actionPDF.triggered.connect(self._print_pdf) self.textEdit.document().modificationChanged.connect( self.actionSave.setEnabled) self.textEdit.document().modificationChanged.connect( self.actionSaveAs.setEnabled) self.styleComboBox.activated.connect(self._text_style) self.fontComboBox.currentTextChanged.connect(self._text_family) self.sizeComboBox.currentTextChanged.connect(self._text_size) self.actionTextBold.triggered.connect(self._text_bold) self.actionTextItalic.triggered.connect(self._text_italic) self.actionTextUnderline.triggered.connect(self._text_underline) self.actionTextColor.triggered.connect(self._text_color) self.actionTextLeft.triggered.connect(self._text_align) self.actionTextRight.triggered.connect(self._text_align) self.actionTextCenter.triggered.connect(self._text_align) self.actionTextJustify.triggered.connect(self._text_align) self.actionUndo.triggered.connect(self.textEdit.undo) self.actionRedo.triggered.connect(self.textEdit.redo) self._font_changed(self.textEdit.font()) self._color_changed(self.textEdit.textColor()) self._alignment_changed(self.textEdit.alignment()) self.actionSave.setEnabled(self.textEdit.document().isModified()) self.actionUndo.setEnabled(self.textEdit.document().isUndoAvailable()) self.actionRedo.setEnabled(self.textEdit.document().isRedoAvailable()) QApplication.clipboard().dataChanged.connect( self._clipboard_data_changed) def _save(self): if not self._file_name: return self._save_as() if self._file_name.startswith(':/'): return self._save_as() writer = QTextDocumentWriter(self._file_name) success = writer.write(self.textEdit.document()) if success: self.statusbar.showMessage('Сохранено успешно') else: self.statusbar.showMessage('Ошибка сохранения') def _save_as(self): dialog = QFileDialog(self, 'Сохранить как...') dialog.setAcceptMode(QFileDialog.AcceptSave) mime_types = ["text/html", "text/plain", "application/vnd.oasis.opendocument.text"] dialog.setMimeTypeFilters(mime_types) dialog.setDefaultSuffix("html") if dialog.exec_() != QDialog.Accepted: self.statusbar.showMessage('Сохранение отменено') return False self._file_name = dialog.selectedFiles()[0] return self._save() def _print(self): printer = QPrinter(QPrinter.HighResolution) self.print_dialog = QPrintDialog(printer, self) if self.textEdit.textCursor().hasSelection(): self.print_dialog.addEnabledOption(QPrintDialog.PrintSelection) self.print_dialog.setWindowTitle('Печать') if self.print_dialog.exec_() == QDialog.accepted: self.textEdit.print(printer) self.print_dialog = None def _print_preview(self): printer = QPrinter(QPrinter.HighResolution) self.preview_dialog = QPrintPreviewDialog(printer, self) self.preview_dialog.paintRequested.connect( self._actually_print_preview) self.preview_dialog.exec_() def _browser(self, not_open=False): filename = f'{self.settings["tempdir"]}/temp_report.html' writer = QTextDocumentWriter(filename) writer.write(self.textEdit.document()) if not not_open: webbrowser.open_new(filename) def _actually_print_preview(self, printer: QPrinter): self.textEdit.print(printer) def _print_pdf(self): dialog = QFileDialog(self, 'Сохранить в PDF') dialog.setAcceptMode(QFileDialog.AcceptSave) dialog.setMimeTypeFilters(['application/pdf']) dialog.setDefaultSuffix('pdf') if dialog.exec_() != QDialog.Accepted: return name = dialog.selectedFiles()[0] self._browser(True) pdfkit.from_file(f'{self.settings["tempdir"]}/temp_report.html', name) self.statusbar.showMessage('Экспорт успешен') if platform.system() == 'Darwin': # macOS subprocess.call(('open', name)) elif platform.system() == 'Windows': # Windows os.startfile(name) else: # linux variants subprocess.call(('xdg-open', name)) def _text_bold(self): fmt = QTextCharFormat() fmt.setFontWeight(QFont.Bold if self.actionTextBold.isChecked() else QFont.Normal) self._merge_text_format(fmt) def _text_italic(self): fmt = QTextCharFormat() fmt.setFontItalic(self.actionTextItalic.isChecked()) self._merge_text_format(fmt) def _text_underline(self): fmt = QTextCharFormat() fmt.setFontUnderline(self.actionTextUnderline.isChecked()) self._merge_text_format(fmt) def _merge_text_format(self, format): cursor = self.textEdit.textCursor() if not cursor.hasSelection(): cursor.select(QTextCursor.WordUnderCursor) cursor.mergeCharFormat(format) self.textEdit.mergeCurrentCharFormat(format) def _cursor_position_changed(self): self._alignment_changed(self.textEdit.alignment()) text_list = self.textEdit.textCursor().currentList() if text_list: list_formats = [ QTextListFormat.ListDisc, QTextListFormat.ListCircle, QTextListFormat.ListSquare, QTextListFormat.ListDecimal, QTextListFormat.ListLowerAlpha, QTextListFormat.ListUpperAlpha, QTextListFormat.ListLowerRoman, QTextListFormat.ListUpperRoman ] try: list_index = list_formats.index(text_list.format().style()) except ValueError: list_index = -1 self.styleComboBox.setCurrentIndex(list_index) else: heading_level = self.textEdit.textCursor().blockFormat() \ .headingLevel() self.styleComboBox.setCurrentIndex( heading_level + 8 if heading_level else 0) def _current_char_format_changed(self, format): self._font_changed(format.font()) self._color_changed(format.foreground().color()) def _text_style(self, index: int): styles = { 1: QTextListFormat.ListDisc, 2: QTextListFormat.ListCircle, 3: QTextListFormat.ListSquare, 4: QTextListFormat.ListDecimal, 5: QTextListFormat.ListLowerAlpha, 6: QTextListFormat.ListUpperAlpha, 7: QTextListFormat.ListLowerRoman, 8: QTextListFormat.ListUpperRoman } cursor = self.textEdit.textCursor() try: style = styles[index] except KeyError: style = None cursor.beginEditBlock() block_fmt = cursor.blockFormat() if style is None: block_fmt.setObjectIndex(-1) heading_level = index - 9 + 1 if index >= 9 else 0 block_fmt.setHeadingLevel(heading_level) cursor.setBlockFormat(block_fmt) size = 4 - heading_level if heading_level else 0 fmt = QTextCharFormat() fmt.setFontWeight(QFont.Bold if heading_level else QFont.Normal) fmt.setProperty(QTextFormat.FontSizeAdjustment, size) cursor.select(QTextCursor.LineUnderCursor) cursor.mergeCharFormat(fmt) self.textEdit.mergeCurrentCharFormat(fmt) else: list_fmt = QTextListFormat() if cursor.currentList(): list_fmt = cursor.currentList().format() else: list_fmt.setIndent(block_fmt.indent() + 1) block_fmt.setIndent(0) cursor.setBlockFormat(block_fmt) list_fmt.setStyle(style) cursor.createList(list_fmt) cursor.endEditBlock() def _text_family(self, font: str): fmt = QTextCharFormat() fmt.setFontFamily(font) self._merge_text_format(fmt) def _text_size(self, size: str): size = float(size) fmt = QTextCharFormat() fmt.setFontPointSize(size) self._merge_text_format(fmt) def _text_color(self): col = QColorDialog.getColor(self.textEdit.textColor(), self) if not col.isValid(): return fmt = QTextCharFormat() fmt.setForeground(col) self._merge_text_format(fmt) self._color_changed(col) def _text_align(self): action = self.sender() if action == self.actionTextLeft: self.textEdit.setAlignment(Qt.AlignLeft | Qt.AlignAbsolute) elif action == self.actionTextCenter: self.textEdit.setAlignment(Qt.AlignHCenter) elif action == self.actionTextRight: self.textEdit.setAlignment(Qt.AlignRight | Qt.AlignAbsolute) elif action == self.actionTextJustify: self.textEdit.setAlignment(Qt.AlignJustify) def _font_changed(self, font): self.fontComboBox.setCurrentIndex(self.fontComboBox.findText( QFontInfo(font).family())) self.sizeComboBox.setCurrentIndex(self.sizeComboBox.findText( str(int(font.pointSize())))) self.actionTextBold.setChecked(font.bold()) self.actionTextItalic.setChecked(font.italic()) self.actionTextUnderline.setChecked(font.underline()) def _color_changed(self, color): pass def _alignment_changed(self, alignment): [a.setChecked(False) for a in (self.actionTextLeft, self.actionTextRight, self.actionTextCenter, self.actionTextJustify)] if alignment & Qt.AlignLeft: self.actionTextLeft.setChecked(True) elif alignment & Qt.AlignHCenter: self.actionTextCenter.setChecked(True) elif alignment & Qt.AlignRight: self.actionTextRight.setChecked(True) elif alignment & Qt.AlignJustify: self.actionTextJustify.setChecked(True) def _clipboard_data_changed(self): md = QApplication.clipboard().mimeData() if md: self.actionTextPaste.setEnabled(md.hasText())