def _print(self): dialog = QPrintDialog(self) if dialog.exec_() != QPrintDialog.Accepted: return printer = dialog.printer() currentView = self.mainView.currentWidget() viewPrinter = ViewPrinter(printer, currentView) currentView.fitViewsForPrint(viewPrinter) viewPrinter.render()
def __printPdfRequested(self, frame): """ Private slot to handle a print to PDF request. @param frame reference to the frame to be printed (QWebFrame) """ printer = QPrinter(mode=QPrinter.HighResolution) if Preferences.getPrinter("ColorMode"): printer.setColorMode(QPrinter.Color) else: printer.setColorMode(QPrinter.GrayScale) printerName = Preferences.getPrinter("PrinterName") if printerName: printer.setPrinterName(printerName) printer.setOutputFormat(QPrinter.PdfFormat) name = frame.url().path().rsplit('/', 1)[-1] if name: name = name.rsplit('.', 1)[0] name += '.pdf' printer.setOutputFileName(name) printDialog = QPrintDialog(printer, self) if printDialog.exec_() == QDialog.Accepted: try: frame.print_(printer) except AttributeError: E5MessageBox.critical( self, self.tr("eric6 Web Browser"), self.tr( """<p>Printing is not available due to a bug in""" """ PyQt5. Please upgrade.</p>""")) return
def printDiagram(self): """ Public slot called to print the diagram. """ printer = QPrinter(mode=QPrinter.ScreenResolution) printer.setFullPage(True) if Preferences.getPrinter("ColorMode"): printer.setColorMode(QPrinter.Color) else: printer.setColorMode(QPrinter.GrayScale) if Preferences.getPrinter("FirstPageFirst"): printer.setPageOrder(QPrinter.FirstPageFirst) else: printer.setPageOrder(QPrinter.LastPageFirst) printer.setPageMargins( Preferences.getPrinter("LeftMargin") * 10, Preferences.getPrinter("TopMargin") * 10, Preferences.getPrinter("RightMargin") * 10, Preferences.getPrinter("BottomMargin") * 10, QPrinter.Millimeter ) printerName = Preferences.getPrinter("PrinterName") if printerName: printer.setPrinterName(printerName) printDialog = QPrintDialog(printer, self) if printDialog.exec_(): super(UMLGraphicsView, self).printDiagram( printer, self.diagramName)
def slotPrint(self): # 新建一个QPrinter对象 printer=QPrinter() # 创建一个QPrintDialog对象,参数为QPrinter对象 printDialog=QPrintDialog(printer,self) ''' 判断打印对话框显示后用户是否单击“打印”按钮,若单击“打印”按钮, 则相关打印属性可以通过创建QPrintDialog对象时使用的QPrinter对象获得, 若用户单击“取消”按钮,则不执行后续的打印操作。 ''' if printDialog.exec_(): # 创建一个QPainter对象,并指定绘图设备为一个QPrinter对象。 painter=QPainter(printer) # 获得QPainter对象的视口矩形 rect=painter.viewport() # 获得图像的大小 size=self.image.size() # 按照图形的比例大小重新设置视口矩形 size.scale(rect.size(),Qt.KeepAspectRatio) painter.setViewport(rect.x(),rect.y(),size.width(),size.height()) # 设置QPainter窗口大小为图像的大小 painter.setWindow(self.image.rect()) # 打印 painter.drawImage(0,0,self.image)
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): 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 print_(self): dialog = QPrintDialog(self.printer, self) if dialog.exec_(): painter = QPainter(self.printer) rect = painter.viewport() size = self.imageLabel.pixmap().size() size.scale(rect.size(), Qt.KeepAspectRatio) painter.setViewport(rect.x(), rect.y(), size.width(), size.height()) painter.setWindow(self.imageLabel.pixmap().rect()) painter.drawPixmap(0, 0, self.imageLabel.pixmap())
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): document = self.textEdit.document() printer = QPrinter() dlg = QPrintDialog(printer, self) if dlg.exec_() != QDialog.Accepted: return document.print_(printer) self.statusBar().showMessage("Ready", 2000)
def slotPrint(self): printer = QPrinter() printDialog = QPrintDialog() if printDialog.exec_(): painter = QPainter(printer) rect = painter.viewport() size = self.image.size() size.scale(rect.size(), Qt.KeepAspectRatio) painter.setViewport(rect.x(), rect.y(), size.width(), size.height()) painter.setWindow(self.image.rect()) painter.drawImage(0, 0, self.image)
def print_(self): dialog = QPrintDialog(self.printer, self) if dialog.exec_(): painter = QPrinter(self.printer) rect = painter.viewport() size = self.imageLabel.pixmap().size() size.scale(rect.size(), Qt.KeepAspectRatio) painter.setViewport(rect.x(), rect.y(), size.width(), size.height()) painter.setWindow(self.imageLabel.pixmap().rect()) painter.drawPixmap(0, 0, self.imageLabel.pixmap())
def printText(self): document = self.text.document() printer = QPrinter() dlg = QPrintDialog(printer, self) if dlg.exec_() != QtWidgets.QDialog.Accepted: return document.print_(printer) self.statusBar().showMessage("打印成功")
def printText(self): document = self.text.document() printer = QPrinter() dlg = QPrintDialog(printer, self) if dlg.exec_() != QtWidgets.QDialog.Accepted: return document.print_(printer) self.statusBar().showMessage("打印成功", 2000)
def slot_canvasPrint(self): self.scene.clearSelection() self.fExportPrinter = QPrinter() dialog = QPrintDialog(self.fExportPrinter, self) if dialog.exec_(): painter = QPainter(self.fExportPrinter) painter.save() painter.setRenderHint(QPainter.Antialiasing) painter.setRenderHint(QPainter.TextAntialiasing) self.scene.render(painter) painter.restore()
def print_img(self): dialog = QPrintDialog(self.printer, self) if dialog.exec_(): painter = QPainter(self.printer) rect = painter.viewport() if self.pixmap.width() > self.pixmap.height(): self.pixmap = self.pixmap.transformed(QTransform().rotate(90)) size = self.pixmap.size() size.scale(rect.size(), Qt.KeepAspectRatio) painter.setViewport(rect.x(), rect.y(), size.width(), size.height()) painter.setWindow(self.pixmap.rect()) painter.drawPixmap(0, 0, self.pixmap)
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 printDialog(self): dialog = QPrintDialog(self.printer, self) if dialog.exec_(): painter = QPainter(self.printer) pixmap = self.grab() rect = painter.viewport() size = pixmap.size() size.scale(rect.size(), Qt.KeepAspectRatio) painter.setViewport(rect.x(), rect.y(), size.width(), size.height()) painter.setWindow(pixmap.rect()) painter.drawPixmap(0, 0, pixmap)
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 printBrowserPdf(self, browser=None): """ Public slot called to print the displayed page to PDF. @param browser reference to the browser to be printed (HelpBrowser) """ if browser is None: browser = self.currentBrowser() name = WebBrowserTools.getFileNameFromUrl(browser.url()) if name: name = name.rsplit('.', 1)[0] name += '.pdf' if hasattr(browser.page(), "printToPdf"): from .Tools.PrintToPdfDialog import PrintToPdfDialog if not name: name = "printout.pdf" dlg = PrintToPdfDialog(name, self) if dlg.exec_() == QDialog.Accepted: filePath, pageLayout = dlg.getData() if filePath: if os.path.exists(filePath): res = E5MessageBox.warning( self, self.tr("Print to PDF"), self.tr("""<p>The file <b>{0}</b> exists""" """ already. Shall it be""" """ overwritten?</p>""").format(filePath), E5MessageBox.StandardButtons(E5MessageBox.No | E5MessageBox.Yes), E5MessageBox.No) if res == E5MessageBox.No: return browser.page().printToPdf( lambda pdf: self.__pdfGeneratedForSave(filePath, pdf), pageLayout) elif Globals.isLinuxPlatform(): printer = QPrinter(mode=QPrinter.HighResolution) if Preferences.getPrinter("ColorMode"): printer.setColorMode(QPrinter.Color) else: printer.setColorMode(QPrinter.GrayScale) printerName = Preferences.getPrinter("PrinterName") if printerName: printer.setPrinterName(printerName) printer.setOutputFormat(QPrinter.PdfFormat) if name: printer.setOutputFileName(name) printer.setResolution(Preferences.getPrinter("Resolution")) printDialog = QPrintDialog(printer, self) if printDialog.exec_() == QDialog.Accepted: browser.render(printer)
def __print(self): layout_name = self.dialogui.comboBox_layouts.currentText() layout_item = self.projectLayoutManager.layoutByName(layout_name) actual_printer = QgsLayoutExporter(layout_item) printdialog = QPrintDialog(self.printer) if printdialog.exec_() != QDialog.Accepted: return success = actual_printer.print(self.printer, QgsLayoutExporter.PrintExportSettings()) if success != 0: QMessageBox.warning(self.iface.mainWindow(), self.tr("Print Failed"), self.tr("Failed to print the layout."))
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 printdialog(self): # """ # 这个函数就是告诉我们调用QPrintDialog准备进行打印了。 # QPrintDialog类提供了一个用于指定打印机配置的对话框。对话框允许用户更改文档相关设置,如纸张尺寸和方向,打印类型(颜色或灰度),页面范围和打印份数。 # 还提供控制以使用户可以从可用的打印机中进行选择,包括任何配置的网络打印机。通常,QPrintDialog对象使用QPrinter对象构造,并使用exec()函数执行。 # # """ printdialog = QPrintDialog(self.printer, self) # """ # 在我们选择好打印机等等后,点击打印(即对话框被用户接受,则QPrinter对象被正确配置为打印),我们会调用QTextEdit中的print方法进行相关的打印 # """ if QDialog.Accepted == printdialog.exec_(): self.tx.print(self.printer)
def print_(self): printer = QPrinter(QPrinter.HighResolution) printDialog = QPrintDialog(printer, self) if printDialog.exec_() == QPrintDialog.Accepted: painter = QPainter(printer) rect = painter.viewport() size = self.image.size() size.scale(rect.size(), Qt.KeepAspectRatio) painter.setViewport(rect.x(), rect.y(), size.width(), size.height()) painter.setWindow(self.image.rect()) painter.drawImage(0, 0, self.image) painter.end()
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 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 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_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 slotPrint(self): import cups import subprocess from PyQt5.QtPrintSupport import QPrintDialog from PyQt5.QtPrintSupport import QPrinter from PyQt5 import QtGui croppedFilename = "%s-cropped.pdf" % splitext( str_unicode(self.fileName))[0] # printerCon = cups.Connection() printer = QPrinter() printDlg = QPrintDialog(printer) if printDlg.exec() == QDialog.Accepted: printerName = printer.printerName() cmdLine = ['lp', '-d', printerName] cmdLine += ['-n', str(printer.copyCount())] cmdLine += ['-o', 'fit-to-page' ] # We want to print out the cropped PDF anyway. # Handle duplex if printer.duplex() == QPrinter.DuplexNone: cmdLine += ['-o', 'Duplex=None'] if printer.duplex() == QPrinter.DuplexLongSide: cmdLine += ['-o', 'Duplex=DuplexNoTumble'] if printer.duplex() == QPrinter.DuplexShortSide: cmdLine += ['-o', 'Duplex=DuplexTumble'] # Orientation if printer.pageLayout().orientation() == QPageLayout.Landscape: cmdLine += ['-o', 'landscape'] # Color mode if printer.colorMode() == QPrinter.GrayScale: cmdLine += ['-o', 'ColorMode=Grayscale'] if printer.colorMode() == QPrinter.Color: cmdLine += ['-o', 'ColorMode=Color'] # Page size pagesizeid_to_pagesize = {} for prop_name in QPageSize.__dict__.keys(): if type(QPageSize.__dict__[prop_name]) == type( QPageSize.PageSizeId()): pagesizeid_to_pagesize[ QPageSize.__dict__[prop_name]] = prop_name cmdLine += [ '-o', 'media=' + pagesizeid_to_pagesize[printer.pageLayout().pageSize().id()] ] cmdLine.append(croppedFilename) # printersLst = printerCon.getPrinters() # printer = QInputDialog.getItem(self, "Please select printer", "", list(printersLst.keys())) print('Print command line: ' + ' '.join(cmdLine)) subprocess.check_call(cmdLine)
def print_file(self): dialog = QPrintDialog(self.printer, self) if dialog.exec_(): painter = QPainter(self.printer) rect = painter.viewport() # auto landscape or portrait printing depending on picture if self.qpixmap_pixel.width() > self.qpixmap_pixel.height(): self.qpixmap_pixel = self.qpixmap_pixel.transformed(QTransform().rotate(90)) size = self.qpixmap_pixel.size() size.scale(rect.size(), Qt.KeepAspectRatio) painter.setViewport(rect.x(), rect.y(), size.width(), size.height()) painter.setWindow(self.qpixmap_pixel.rect()) painter.drawPixmap(0, 0, self.qpixmap_pixel)
def printCodes(): #action which is triggered when the user selects 'Print' menu item if mw == None: raise Exception('Mainwindow is not initialized') else: print('printing...') printer = QPrinter() dlg = QPrintDialog(printer) if dlg.exec() == QDialog.Accepted: painter = QPainter() painter.begin(printer) drawLabels(painter, mw.labels, printer) painter.end()
def printing(self): """ Docstring. """ document = self.gamePane.document() printer = QPrinter() dialog = QPrintDialog(printer, self) if dialog.exec() != QDialog.Accepted: return document.print(printer) self.statusBar().showMessage("Ready.", 2000)
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 filePrint(self): if self.currentImage.isNull(): return if self.printer is None: self.printer = QPrinter(QPrinter.HighResolution) self.printer.setPageSize(QPrinter.Letter) form = QPrintDialog(self.printer, self) if form.exec_(): painter = QPainter(self.printer) rect = painter.viewport() size = self.currentImage.size() size.scale(rect.size(), Qt.KeepAspectRatio) painter.setViewport(rect.x(), rect.y(), size.width(), size.height()) painter.drawImage(0, 0, self.currentImage)
def on_print(self): """Print event handler""" # Create printer printer = QPrinter(mode=QPrinter.HighResolution) # Get print area self.print_area = PrintAreaDialog(self, self.grid).area if self.print_area is None: return # Create print dialog dialog = QPrintDialog(printer, self) if dialog.exec_() == QPrintDialog.Accepted: self.on_paint_request(printer)
def print_dialog(self): print_dialog = QPrintDialog(self.printer, self) # 打印对话框点击确认再执行 if QDialog.Accepted == print_dialog.exec_(): # 打印的第一种方法直接执行控件的打印方法 # self.text_edit.print(self.printer) # 打印的第二种方法还能画到printer对象里面的方式打印图片 screen = self.text_edit.grab() # .QPixmap对象 painter = QPainter() painter.begin(self.printer) painter.drawPixmap(0, 0, screen) painter.end() print('print end')
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 slot_print(self): """打印动作触发的槽函数, 用于打印, 会创建一个QPrinter给QPainter用作绘画""" printer = QPrinter() printer.setOutputFormat(QPrinter.PdfFormat) print_dialog = QPrintDialog(printer, parent=self) # 打印对话框, 用于设置printer if print_dialog.exec_(): painter = QPainter(printer) rect = painter.viewport() # 实例化视图窗口 size = self.image.size() # 获取图片的尺寸 size.scale(rect.size(), Qt.KeepAspectRatio) # Qt.KeepAspectRatio 保持纵横比 painter.setViewport(rect.x(), rect.y(), size.width(), size.height()) #设置窗口的大小为图片的磁村,并在窗口内绘制 painter.setWindow(self.image.rect()) painter.drawImage(0, 0, self.image)
def print(self, preview: bool = False) -> None: """Print the current widget. **syntax:** ``:print [--preview]`` optional arguments: * ``--preview``: Show preview dialog before printing. """ if self._widget is None: raise api.commands.CommandError("No widget to print") logging.debug("Starting print dialog") def handle_print() -> None: # We only use handle_print in the function below, None was caught above self._widget = cast(PrintWidget, self._widget) self._widget.print(dialog.printer(), auto_apply_orientation) if preview: dialog = QPrintPreviewDialog() # See https://github.com/stlehmann/PyQt5-stubs/pull/7 # TODO Remove the type: ignore once the PR was merged and a new version is # on PyPi dialog.paintRequested.connect(handle_print) # type: ignore auto_apply_orientation = False else: dialog = QPrintDialog() auto_apply_orientation = True dialog.open(handle_print)
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 printpage(self, preview=False, count: {'special': 'count'} = None): """Print the current/[count]th tab. Args: preview: Show preview instead of printing. count: The tab index to print, or None. """ if not qtutils.check_print_compat(): # WORKAROUND (remove this when we bump the requirements to 5.3.0) raise cmdexc.CommandError( "Printing on Qt < 5.3.0 on Windows is broken, please upgrade!") tab = self._cntwidget(count) if tab is not None: if preview: diag = QPrintPreviewDialog() diag.setAttribute(Qt.WA_DeleteOnClose) diag.setWindowFlags(diag.windowFlags() | Qt.WindowMaximizeButtonHint | Qt.WindowMinimizeButtonHint) diag.paintRequested.connect(tab.print) diag.exec_() else: diag = QPrintDialog() diag.setAttribute(Qt.WA_DeleteOnClose) diag.open(lambda: tab.print(diag.printer()))
def __printDiagram(self): """ Private slot called to print the diagram. """ printer = QPrinter(mode=QPrinter.ScreenResolution) printer.setFullPage(True) if Preferences.getPrinter("ColorMode"): printer.setColorMode(QPrinter.Color) else: printer.setColorMode(QPrinter.GrayScale) if Preferences.getPrinter("FirstPageFirst"): printer.setPageOrder(QPrinter.FirstPageFirst) else: printer.setPageOrder(QPrinter.LastPageFirst) printer.setPrinterName(Preferences.getPrinter("PrinterName")) printDialog = QPrintDialog(printer, self) if printDialog.exec_(): self.__print(printer)
def __printImage(self): """ Private slot to handle the Print Image menu action. """ if self.mainWidget is None: E5MessageBox.critical( self, self.tr("Print Image"), self.tr("""There is no UI file loaded.""")) return settings = Preferences.Prefs.settings printer = QPrinter(QPrinter.HighResolution) printer.setFullPage(True) printerName = Preferences.getPrinter("UIPreviewer/printername") if printerName: printer.setPrinterName(printerName) printer.setPageSize( QPrinter.PageSize(int(settings.value("UIPreviewer/pagesize")))) printer.setPageOrder( QPrinter.PageOrder(int(settings.value("UIPreviewer/pageorder")))) printer.setOrientation(QPrinter.Orientation( int(settings.value("UIPreviewer/orientation")))) printer.setColorMode( QPrinter.ColorMode(int(settings.value("UIPreviewer/colormode")))) printDialog = QPrintDialog(printer, self) if printDialog.exec_() == QDialog.Accepted: self.statusBar().showMessage(self.tr("Printing the image...")) self.__print(printer) settings.setValue("UIPreviewer/printername", printer.printerName()) settings.setValue("UIPreviewer/pagesize", printer.pageSize()) settings.setValue("UIPreviewer/pageorder", printer.pageOrder()) settings.setValue("UIPreviewer/orientation", printer.orientation()) settings.setValue("UIPreviewer/colormode", printer.colorMode()) self.statusBar().showMessage( self.tr("Image sent to printer..."), 2000)
def show_dialog(self) -> None: """Print with a QPrintDialog.""" self.check_printer_support() def print_callback(ok: bool) -> None: """Called when printing finished.""" if not ok: message.error("Printing failed!") diag.deleteLater() def do_print() -> None: """Called when the dialog was closed.""" self.to_printer(diag.printer(), print_callback) diag = QPrintDialog(self._tab) if utils.is_mac: # For some reason we get a segfault when using open() on macOS ret = diag.exec_() if ret == QDialog.Accepted: do_print() else: diag.open(do_print)
def __printRequested(self, frame): """ Private slot to handle a print request. @param frame reference to the frame to be printed (QWebFrame) """ printer = QPrinter(mode=QPrinter.HighResolution) if Preferences.getPrinter("ColorMode"): printer.setColorMode(QPrinter.Color) else: printer.setColorMode(QPrinter.GrayScale) if Preferences.getPrinter("FirstPageFirst"): printer.setPageOrder(QPrinter.FirstPageFirst) else: printer.setPageOrder(QPrinter.LastPageFirst) printer.setPageMargins( Preferences.getPrinter("LeftMargin") * 10, Preferences.getPrinter("TopMargin") * 10, Preferences.getPrinter("RightMargin") * 10, Preferences.getPrinter("BottomMargin") * 10, QPrinter.Millimeter ) printerName = Preferences.getPrinter("PrinterName") if printerName: printer.setPrinterName(printerName) printDialog = QPrintDialog(printer, self) if printDialog.exec_() == QDialog.Accepted: try: frame.print_(printer) except AttributeError: E5MessageBox.critical( self, self.tr("eric6 Web Browser"), self.tr( """<p>Printing is not available due to a bug in""" """ PyQt5. Please upgrade.</p>""")) return
def on_print_requested(self, frame): """Handle printing when requested via javascript.""" if not qtutils.check_print_compat(): message.error(self._win_id, "Printing on Qt < 5.3.0 on Windows is " "broken, please upgrade!", immediately=True) return printdiag = QPrintDialog() printdiag.setAttribute(Qt.WA_DeleteOnClose) printdiag.open(lambda: frame.print(printdiag.printer()))
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 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 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 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 _q_print(self): printDialog = QPrintDialog(self.printer, self) if printDialog.exec_() == QDialog.Accepted: self.preview.print_() self.accept()
def on_print_requested(self, frame): """Handle printing when requested via javascript.""" printdiag = QPrintDialog() printdiag.setAttribute(Qt.WA_DeleteOnClose) printdiag.open(lambda: frame.print(printdiag.printer()))
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)
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()