def printNote(self): printer = QPrinter(QPrinter.HighResolution) printer.setCreator(__appname__ + ' ' + __version__) printer.setDocName(self.notesTree.currentItem().text(0)) printdialog = QPrintDialog(printer, self) if printdialog.exec() == QDialog.Accepted: self.notesView.print_(printer)
def _print_report(self): printer = QPrinter() print_dialog = QPrintDialog(printer, self) print_dialog.setWindowTitle("Print report") if print_dialog.exec_() != QDialog.Accepted: return self.report_view.print_(printer)
def printFile(self): # Needs some work... printDialog = QPrintDialog(self.printer, py_de) if printDialog.exec_() == QDialog.Accepted: margin = 10 pageNum = 1 yPos = 0 printJob = QPainter() printJob.begin(self.printer) printJob.setFont(self.font) fm = printJob.fontMetrics() for i in range(self.textEdit.lines()): if margin + yPos > self.printer.height() - margin: pageNum += 1 self.printer.newPage() yPos = 0 printJob.drawText(margin, # X margin + yPos, # Y self.printer.width(), # Width self.printer.height(),# Height QtCore.Qt.AlignTop, # Alignment self.textEdit.text(i - 1)# The text to print ) yPos += fm.lineSpacing() printJob.end
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 askPrinter(): printer = QPrinter() select = QPrintDialog(printer) if select.exec_(): return printer else: return None
def printDocument(self): dialog = QPrintDialog() if not dialog.exec_(): return self.printer = dialog.printer() self.imprimir(self.printer) self.document.load(self.editmodel)
def _onShortcutPrint(self): """Ctrl+P handler. Show dialog, print file """ dialog = QPrintDialog(self) if dialog.exec_() == QDialog.Accepted: printer = dialog.printer() self.print_(printer)
def print_photo(self): print_dialog = QPrintDialog(self._printer,self) if print_dialog.exec_() == QDialog.Accepted: painter = QPainter(self._printer) rect = painter.viewport() size = self._lbl_photo.pixmap().size() size.scale(rect.size(), Qt.KeepAspectRatio) painter.setViewport(rect.x(), rect.y(), size.width(), size.height()) painter.setWindow(self._lbl_photo.pixmap().rect()) painter.drawPixmap(0, 0, self._lbl_photo.pixmap())
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 open_print_dialog(self): """ This member function calls print routine. """ aPrinter = QPrinter(QPrinter.HighResolution) printDialog = QPrintDialog(aPrinter) # need this to make sure we take away focus from # any currently selected legend items self.canvas.clearFocus() if printDialog.exec_() == QDialog.Accepted: io.printer(self.canvas, aPrinter)
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, True) painter.setRenderHint(QPainter.TextAntialiasing, True) self.scene.render(painter) painter.restore()
def printDocument1(self): html = u"" date = QDate.currentDate().toString(self.DATE_FORMAT) address = Qt.escape("Bario francisco mesa").replace(",", "<br>") contact = Qt.escape("Luis Mejia") balance = 5000 html += ("<p align=right><img src=':/logo.png'></p>" "<p> align = right>Greasy hands ltd." "<br>New Lombard Street" "<br>London<br>WC13 4PX<br>%s</p>" "<p>%s</p><p>Dear %s, </p>" "<p>The balance of your account is %s.") % ( date, address, contact, QString("$ %L1").arg( float(balance), 0, "f", 2)) if balance < 0: html += ( "<p><font color =red><b> Please remit the amount owing immediately.</b></font>" ) else: html += "We are delighted to have done business with you." html += ( "</p><p> </p><p>" "<table border=1 cellpadding=2 cellspacing=2><tr><td colspan=3>Transaction</td></tr>" ) transactions = [(QDate.currentDate(), 500), (QDate.currentDate(), 500), (QDate.currentDate(), -500), (QDate.currentDate(), 500)] for date, amount in transactions: color, status = "black", "Credit" if amount < 0: color, status = "red", "Debid" html += ( "<tr>" "<td align= right>%s</td>" "<td>%s</td><td align=right><font color=%s>%s</font></td></tr>" % (date.toString(self.DATE_FORMAT), status, color, QString("$ %L1").arg(float(abs(amount)), 0, "f", 2))) html += ("</table></p><p style='page-break-after=always;'>" "We hope to continue doing business with you</p>") pdialog = QPrintDialog() if pdialog.exec_() == QDialog.Accepted: printer = pdialog.printer() document = QTextDocument() document.setHtml(html) document.print_(printer)
def _print_file(self): self.printer = QPrinter(QPrinter.HighResolution) self.printer.setPageSize(QPrinter.A4) if self._central.obtain_editor().path: fileName = manage_files.get_basename(self._central.obtain_editor().path) fileName = fileName[:fileName.rfind('.')] + '.pdf' else: fileName = 'newDocument.pdf' self.printer.setOutputFileName(fileName) dialog = QPrintDialog(self.printer, self) if dialog.exec_(): self.printer.setDocName(manage_files.get_basename(self._central.obtain_editor().path)) self._central.obtain_editor().document().print_(self.printer)
def on_actionPrint_triggered(self): 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.image.size() size.scale(rect.size(), Qt.KeepAspectRatio) painter.setViewport(rect.x(), rect.y(), size.width(), size.height()) painter.drawImage(0, 0, self.image)
def savePrinter(self): """ Save to printer """ printer = QPrinter() dialog = QPrintDialog(printer, self) dialog.setWindowTitle("Print") if dialog.exec_() != QDialog.Accepted: return doc = QTextDocument() doc.setPlainText(self.txtEdit.text()) doc.print_(printer)
def on_stampa_triggered(self, checked=None): """Slot launched when the user click on the "stampa" button""" if checked is None: return printer = QPrinter() print_dialog = QPrintDialog(printer, self) if print_dialog.exec_() == QDialog.Accepted: printer.setOrientation(QPrinter.Landscape) painter = QPainter() painter.begin(printer) geometry = self.ui_calendar.Table.geometry() self.ui_calendar.Table.setGeometry(printer.pageRect()) self.ui_calendar.Table.render(painter) self.ui_calendar.Table.setGeometry(geometry) painter.end()
def printBill(self): self.saveTab() #save before printing so that changes will be added to print html = self.creator.makePrintfile(self.item) document = QWebView() document.setHtml(html) printer = QPrinter() printer.setOutputFileName(getBillPath() + str(datetime.datetime.now())[0:-7] + '_' + str(self.item.id) + '.pdf') printpreview = QPrintDialog(printer, self) printpreview.exec() document.print(printer)
def savePrinter(self): """ Save to printer """ printer = QPrinter() dialog = QPrintDialog(printer, self) dialog.setWindowTitle("Print") if dialog.exec_() != QDialog.Accepted: return if QtHelper.IS_QT5: # new in v18 self.fileName = printer self.txtEdit.page().toHtml(self.__toPrinter) else: self.txtEdit.print_(printer)
def printCharacter(self): """ Druckt den angezeigten Charakter aus. """ printer = QPrinter(QPrinter.PrinterResolution) printDialog = QPrintDialog(printer, self) if (printDialog.exec_() == QDialog.Accepted): drawSheet = RenderSheet(self.__storage, self.__character, printer, self) try: drawSheet.createSheets() except ErrSpeciesNotExisting as e: MessageBox.exception(self, e.message, e.description)
def savePrinter(self): """ Save to printer """ printer = QPrinter() dialog = QPrintDialog(printer, self) dialog.setWindowTitle("Print") if dialog.exec_() != QDialog.Accepted: return if QtHelper.IS_QT5: # new in v18 self.fileName = printer self.txtEdit.page().toHtml(self.__toPrinter) else: frame = self.txtEdit.page().mainFrame() doc = QTextDocument() doc.setPlainText( frame.toPlainText() ) doc.print_(printer)
def outPrint( self, iface, wdg, mdl, library): # Postscript file rendering doesn't work properly yet. for i in range(0, mdl.rowCount()): if mdl.item(i, 0).data(Qt.CheckStateRole): name = str(mdl.item(i, 2).data(Qt.EditRole)) #return fileName = QFileDialog.getSaveFileName(iface.mainWindow(), "Save As", "Profile of " + name + ".ps", "PostScript Format (*.ps)") if fileName: if library == "Qwt5" and has_qwt: printer = QPrinter() printer.setCreator("QGIS Profile Plugin") printer.setDocName("QGIS Profile") printer.setOutputFileName(fileName) printer.setColorMode(QPrinter.Color) printer.setOrientation(QPrinter.Portrait) dialog = QPrintDialog(printer) if dialog.exec_(): wdg.plotWdg.print_(printer) elif library == "Matplotlib" and has_mpl: wdg.plotWdg.figure.savefig(str(fileName))
def print_file(fileName, printFunction): """This method print a file This method print a file, fileName is the default fileName, and printFunction is a funcion that takes a QPrinter object and print the file, the print method More info on:http://doc.qt.nokia.com/latest/printing.html""" #TODO: Make that the option it's taken from settings. maybe #this should be a class to manage all cases? printer = QPrinter(QPrinter.HighResolution) printer.setPageSize(QPrinter.A4) printer.setOutputFileName(fileName) printer.setDocName(fileName) #PRINT PREVIEW OPTIONS #TODO: the follow imp. dipatch an error on execution time we need to review #if the error belongs to qt # preview = QPrintPreviewDialog(printer) # preview.paintRequested[QPrinter].connect(printFunction) # preview.exec_() dialog = QPrintDialog(printer) if dialog.exec_(): printFunction(printer)
def slotPrint(self): printer = QPrinter() dlg = QPrintDialog(printer, self) dlg.setWindowTitle(app.caption(_("Print"))) if dlg.exec_(): self.webview.print_(printer)
def _onPrint(self): printer = QPrinter() dialog = QPrintDialog(printer, self) if dialog.exec_() != QDialog.Accepted: return self.page.mainFrame().print_(printer)
def showprint(self): self._printbox = QPrintDialog(self) if self._printbox.exec_() == QDialog.Accepted: self.printout()
def handlePrint(self): dialog = QPrintDialog() if dialog.exec_() == QDialog.Accepted: self.handlePaintRequest(dialog.printer())
def onPlotButton(self): """ Batch plots selected geometry items using the selected template and scale. """ # check if one layer is selected if self.ui.LayersComboBox.currentIndex() == -1: QMessageBox.warning(self, tr("Warning"), tr("Select a layer!")) self.ui.LayersComboBox.setFocus() return # check if one composition template is selected if self.ui.TemplateList.selectedItems() == []: QMessageBox.warning(self, tr("Warning"), tr("Select a composer template!")) self.ui.TemplateList.setFocus() return template_filename = QDir(self.templatepath).absoluteFilePath( self.ui.TemplateList.currentItem().text()) # get the scale if self.ui.ScaleCombo.currentText() == "<extent>": scale = -1 else: try: scale = int(self.ui.ScaleCombo.currentText()) except (ValueError): QMessageBox.warning( self, tr("Warning"), tr("Scale must be a positive integer value!")) self.ui.ScaleCombo.setFocus() return if scale <= 0: QMessageBox.warning( self, tr("Warning"), tr("Scale must be a positive integer value!")) self.ui.ScaleCombo.setFocus() return # get composer name composer_name = self.ui.ComposerEdit.text() #check if there are selected items on polygon layers if self.batch_plotting: selected_layer = self.ui.LayersComboBox.itemData( self.ui.LayersComboBox.currentIndex()) selected_polygons = get_features(selected_layer.name(), QGis.Polygon, True) if selected_polygons is None: QMessageBox.warning( self, tr("Warning"), tr("Select at least one polygon on layer '%s'!" % selected_layer.name())) return # check output setting if self.ui.OutputTab.currentIndex() == 0: # to PDF if not self.ui.SingleFileCheckbox.checkState(): if len(self.ui.OutputPDFEdit.text()) == 0: res = QMessageBox.warning( self, tr("Warning"), tr("The filename pattern is empty. A default one will be used." ), QMessageBox.Ok | QMessageBox.Cancel, QMessageBox.Ok) if res == QMessageBox.Cancel: return self.ui.OutputPDFEdit.setText( QgsAtlasComposition(None).filenamePattern()) elif self.ui.OutputTab.currentIndex() == 1: # to Printer # no need for checking pass elif self.ui.OutputTab.currentIndex() == 2: # to Composer View # no need for checking yet pass # get map renderer of map canvas renderer = self.iface.mapCanvas().mapRenderer() self.composition = QgsComposition(renderer) # if plot to Composer View the composition must be set # before loading the template # otherwise composer's item properties doesn't appear if self.ui.OutputTab.currentIndex() == 2: # to Composer View if len(composer_name) == 0: composer = self.iface.createNewComposer() else: composer = self.iface.createNewComposer(composer_name) composer.setComposition(self.composition) # read template file and add to composition template_file = QFile(template_filename) template_file.open(QIODevice.ReadOnly | QIODevice.Text) template_content = template_file.readAll() template_file.close() document = QDomDocument() document.setContent(template_content) self.composition.loadFromTemplate(document) # if batch_plotting is True create an atlas composition if self.batch_plotting: # get composer map item and set new scale and the grid cmap = self.composition.getComposerMapById(0) cmap.setNewScale(scale) cmap.setGridIntervalX(scale / 10) cmap.setGridIntervalY(scale / 10) cmap.setAtlasDriven(True) cmap.setAtlasScalingMode(QgsComposerMap.Fixed) # set atlas composition parameters atlas = self.composition.atlasComposition() atlas.setEnabled(True) atlas.setCoverageLayer(selected_layer) atlas.setHideCoverage(False) atlas.setFilenamePattern(self.ui.OutputPDFEdit.text()) atlas.setSingleFile(self.ui.SingleFileCheckbox.checkState()) atlas.setSortFeatures(False) atlas.setFilterFeatures(True) selected_ids = [f.id() for f in selected_layer.selectedFeatures()] filter_id_string = ','.join([str(sid) for sid in selected_ids]) atlas.setFeatureFilter("$id in (" + filter_id_string + ")") # print the complete atlas composition if self.ui.OutputTab.currentIndex() == 0: # to PDF self.composition.setAtlasMode(QgsComposition.ExportAtlas) if self.pdfpath == "": self.pdfpath = QgsProject.instance().homePath().encode( sys.getfilesystemencoding()) if self.ui.SingleFileCheckbox.checkState(): #print to single pdf (multi-page) outputFileName = QDir( self.pdfpath).absoluteFilePath("qgis.pdf") outputFileName = QFileDialog.getSaveFileName( self, tr("Choose a file name to save the map as"), outputFileName, tr("PDF Format") + " (*.pdf *.PDF)") if not outputFileName: return if not outputFileName.lower().endswith(".pdf"): outputFileName += ".pdf" self.pdfpath = QDir(outputFileName).absolutePath() else: #print to more pdf outputDir = QFileDialog.getExistingDirectory( self, tr("Directory where to save PDF files"), self.pdfpath, QFileDialog.ShowDirsOnly) if not outputDir: return # test directory (if it exists and is writable) if not QDir(outputDir).exists() or not QFileInfo( outputDir).isWritable(): QMessageBox.warning( self, tr("Unable to write into the directory"), tr("The given output directory is not writable. Cancelling." )) return self.pdfpath = outputDir printer = QPrinter() painter = QPainter() if not len(atlas.featureFilterErrorString()) == 0: QMessageBox.warning( self, tr("Atlas processing error"), tr("Feature filter parser error: %s" % atlas.featureFilterErrorString())) return atlas.beginRender() if self.ui.SingleFileCheckbox.checkState(): #prepare for first feature, so that we know paper size to begin with atlas.prepareForFeature(0) self.composition.beginPrintAsPDF(printer, outputFileName) # set the correct resolution self.composition.beginPrint(printer) printReady = painter.begin(printer) if not printReady: QMessageBox.warning( self, tr("Atlas processing error"), tr("Error creating %s." % outputFileName)) return progress = QProgressDialog(tr("Rendering maps..."), tr("Abort"), 0, atlas.numFeatures(), self) QApplication.setOverrideCursor(Qt.BusyCursor) for featureI in range(0, atlas.numFeatures()): progress.setValue(featureI + 1) # process input events in order to allow aborting QCoreApplication.processEvents() if progress.wasCanceled(): atlas.endRender() break if not atlas.prepareForFeature(featureI): QMessageBox.warning(self, tr("Atlas processing error"), tr("Atlas processing error")) progress.cancel() QApplication.restoreOverrideCursor() return if not self.ui.SingleFileCheckbox.checkState(): multiFilePrinter = QPrinter() outputFileName = QDir(outputDir).filePath( atlas.currentFilename()) + ".pdf" self.composition.beginPrintAsPDF( multiFilePrinter, outputFileName) # set the correct resolution self.composition.beginPrint(multiFilePrinter) printReady = painter.begin(multiFilePrinter) if not printReady: QMessageBox.warning( self, tr("Atlas processing error"), tr("Error creating %s." % outputFileName)) progress.cancel() QApplication.restoreOverrideCursor() return self.composition.doPrint(multiFilePrinter, painter) painter.end() else: # start print on a new page if we're not on the first feature if featureI > 0: printer.newPage() self.composition.doPrint(printer, painter) atlas.endRender() if self.ui.SingleFileCheckbox.checkState(): painter.end() QApplication.restoreOverrideCursor() elif self.ui.OutputTab.currentIndex() == 1: # to Printer # if To Printer is selected set the printer # setting up printer if self.printer is None: self.printer = QPrinter() self.printer.setFullPage(True) self.printer.setColorMode(QPrinter.Color) # open printer setting dialog pdlg = QPrintDialog(self.printer, self) pdlg.setModal(True) pdlg.setOptions(QAbstractPrintDialog.None) if not pdlg.exec_() == QDialog.Accepted: return QApplication.setOverrideCursor(Qt.BusyCursor) #prepare for first feature, so that we know paper size to begin with self.composition.setAtlasMode(QgsComposition.ExportAtlas) atlas.prepareForFeature(0) # set orientation if self.composition.paperWidth( ) > self.composition.paperHeight(): self.printer.setOrientation(QPrinter.Landscape) self.printer.setPaperSize( QSizeF(self.composition.paperHeight(), self.composition.paperWidth()), QPrinter.Millimeter) else: self.printer.setOrientation(QPrinter.Portrait) self.printer.setPaperSize( QSizeF(self.composition.paperWidth(), self.composition.paperHeight()), QPrinter.Millimeter) self.printer.setResolution(self.composition.printResolution()) self.composition.beginPrint(self.printer) painter = QPainter(self.printer) if not len(atlas.featureFilterErrorString()) == 0: QMessageBox.warning( self, tr("Atlas processing error"), tr("Feature filter parser error: %s" % atlas.featureFilterErrorString())) QApplication.restoreOverrideCursor() return atlas.beginRender() progress = QProgressDialog(tr("Rendering maps..."), tr("Abort"), 0, atlas.numFeatures(), self) for featureI in range(0, atlas.numFeatures()): progress.setValue(featureI + 1) # process input events in order to allow cancelling QCoreApplication.processEvents() if progress.wasCanceled(): atlas.endRender() break if not atlas.prepareForFeature(featureI): QMessageBox.warning(self, tr("Atlas processing error"), tr("Atlas processing error")) progress.cancel() QApplication.restoreOverrideCursor() return # start print on a new page if we're not on the first feature if featureI > 0: self.printer.newPage() self.composition.doPrint(self.printer, painter) atlas.endRender() painter.end() QApplication.restoreOverrideCursor() elif self.ui.OutputTab.currentIndex() == 2: # to Composer View # create new composer self.composition.setAtlasMode(QgsComposition.PreviewAtlas) composer.composerWindow().on_mActionAtlasPreview_triggered( True) atlas.parameterChanged.emit() # Increase the reference count of the composer object # for not being garbage collected. # If not doing this composer would lost reference and qgis would crash # when referring to this composer object or at quit. ctypes.c_long.from_address(id(composer)).value += 1 else: # if batch_plotting is False open a QgsComposerView with current map canvas cmap = self.composition.getComposerMapById(0) # set the new extent of composer map item newextent = self.iface.mapCanvas().mapRenderer().extent() currentextent = cmap.extent() canvas_ratio = newextent.width() / newextent.height() map_ratio = currentextent.width() / currentextent.height() if map_ratio < canvas_ratio: dh = newextent.width() / map_ratio - newextent.height() newextent.setYMinimum(newextent.yMinimum() - dh / 2) newextent.setYMaximum(newextent.yMaximum() + dh / 2) else: dw = map_ratio * newextent.height() - newextent.width() newextent.setXMinimum(newextent.xMinimum() - dw / 2) newextent.setXMaximum(newextent.xMaximum() + dw / 2) cmap.setNewExtent(newextent) # set the new scale of composer map item if scale > 0: cmap.setNewScale(scale) sc = cmap.scale() # set the grid interval according to the scale cmap.setGridIntervalX(sc / 10) cmap.setGridIntervalY(sc / 10) # Increase the reference count of the composer object # for not being garbage collected. # If not doing this composer would lost reference and qgis would crash # when referring to this composer object or at quit. ctypes.c_long.from_address(id(composer)).value += 1 self.accept()
def pbtnPrintClicked(self): dialog = QPrintDialog() if dialog.exec_() == QDialog.Accepted: self.dlg.txtFeedback.document().print_(dialog.printer())
def print_(doc, filename=None, widget=None): """Prints the popplerqt4.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", "", type("")) 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") 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 printDocument2(self): dialog = QPrintDialog() if not dialog.exec_(): return self.printer = dialog.printer() headFormat = QTextBlockFormat() headFormat.setAlignment(Qt.AlignLeft) headFormat.setTextIndent(self.printer.pageRect().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 cursor.insertBlock(headFormat, headCharFormat) for text in ("Greasy Hands Ltd.", "New Lombard Street", "London", "WC13", QDate.currentDate().toString(self.DATE_FORMAT)): cursor.insertBlock(headFormat, headCharFormat) cursor.insertText(text) cursor.insertBlock(bodyFormat, bodyCharFormat) cursor.insertText("Barrio Francisco Meza") cursor.insertBlock(bodyFormat) cursor.insertBlock(bodyFormat, bodyCharFormat) cursor.insertText("Dear Lyuis") cursor.insertBlock(bodyFormat) cursor.insertBlock(bodyFormat, bodyCharFormat) cursor.insertText( QString("The balance of your account is $ %L1.").arg( float(500.987), 0, "f", 2)) cursor.insertBlock(bodyFormat, redBodyCharFormat) cursor.insertText("Please remit the amount") cursor.insertBlock(bodyFormat, bodyCharFormat) cursor.insertText("Transaction") transactions = [(QDate.currentDate(), 500), (QDate.currentDate(), 500), (QDate.currentDate(), -500), (QDate.currentDate(), 500)] table = cursor.insertTable(len(transactions), 3, tableFormat) row = 0 for date, amount in transactions: cellCursor = table.cellAt(row, 0).firstCursorPosition() cellCursor.setBlockFormat(rightBodyFormat) cellCursor.insertText(date.toString(self.DATE_FORMAT), bodyCharFormat) cellCursor = table.cellAt(row, 1).firstCursorPosition() cellCursor.insertText("Credit", bodyCharFormat) cellCursor = table.cellAt(row, 2).firstCursorPosition() cellCursor.setBlockFormat(rightBodyFormat) cellCursor.insertText( QString("The balance of your account is $ %L1.").arg( float(amount), 0, "f", 2), redBodyCharFormat) row += 1 cursor.setPosition(mainFrame.lastPosition()) cursor.insertBlock(bodyFormat, bodyCharFormat) cursor.insertText("We hope") document.print_(self.printer)