def printProfile(self): printer = QPrinter(QPrinter.HighResolution) printer.setOutputFormat(QPrinter.PdfFormat) printer.setPaperSize(QPrinter.A4) printer.setOrientation(QPrinter.Landscape) printpreviewdlg = QPrintPreviewDialog() printpreviewdlg.paintRequested.connect(self.printRequested) printpreviewdlg.exec_()
def __createPdf(self, savePath): """ Diese Funktion druckt den Charakter in ein PDF-Dokument. """ # Wenn Unterverzeichnis nicht existiert, erstelle es dirname = os.path.dirname(savePath) if not os.path.exists(dirname): os.makedirs(dirname) printer = QPrinter(QPrinter.PrinterResolution) #printer = QPrinter() printer.setOutputFormat(QPrinter.PdfFormat) printer.setPaperSize(QPrinter.A4) printer.setFullPage(True) printer.setOutputFileName(savePath) drawSheet = RenderSheet(self.__storage, self.__character, printer, self) try: drawSheet.createSheets() except ErrSpeciesNotExisting as e: MessageBox.exception(self, e.message, e.description)
def savePdf(self): """ Save to pdf file """ fileName = QFileDialog.getSaveFileName( self, 'Save to PDF', "", "PDF file (*.pdf);;All Files (*.*)") # new in v17.1 if QtHelper.IS_QT5: _filename, _type = fileName else: _filename = fileName # end of new if _filename: printer = QPrinter(QPrinter.HighResolution) printer.setPageSize(QPrinter.A4) printer.setColorMode(QPrinter.Color) printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(_filename) doc = QTextDocument() if self.toXml: doc.setPlainText(self.txtEdit.text()) else: doc.setHtml(self.txtEdit.toHtml()) doc.print_(printer)
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 on_actionPreview_activated( self ): printer = QPrinter() printer.setPageSize( QPrinter.Letter ) web = "balancegeneral.php?date=%d+%d" % ( self.dtPicker.date().month() , self.dtPicker.date().year() ) report = frmReportes( web , printer, self ) report.exec_()
def printPage(ok): printer = QPrinter() printer.setOutputFormat(QPrinter.PdfFormat) printer.setOrientation(QPrinter.Landscape) printer.setPageMargins(0.1,0.1,0.1,0.1, QPrinter.Millimeter) printer.setOutputFileName(sys.argv[2]) view.print_(printer) app.exit()
def on_actionFitPage_triggered(self): papersize = self._getPaperSize() printer = QPrinter() printer.setPaperSize(papersize) widthInPixels = printer.pageRect().width() maxColumns = self.songProperties.maxColumns(widthInPixels) self.widthSpinBox.setValue(maxColumns) self.scoreScene.reBuild()
def imprimir(self): print('Prepandando impresion') self.printer = QPrinter(QPrinter.HighResolution) self.printer.setPageSize(QPrinter.A4) self.printer.setOrientation(QPrinter.Portrait) self.printer.setPageMargins(10, 10, 10, 10, QPrinter.Millimeter) self.navegador.print_(self.printer)
def printWindow(self, printer=None): if not printer: printer = QPrinter() printer.setFullPage(True) printer.setPageSize(QPrinter.A4) dialog = QPrintDialog(printer, self) dialog.setWindowTitle(QCoreApplication.translate('QwtPlot', 'Print Document')) if dialog.exec_() != QDialog.Accepted: return self.plot.print_(printer, QwtPlotPrintFilter())
def on_actionPrint_triggered(self): if self._printer is None: self._printer = QPrinter() self._printer = QPrinter(QPrinterInfo(self._printer), QPrinter.HighResolution) self._printer.setPaperSize(self._getPaperSize()) dialog = QPrintPreviewDialog(self._printer, parent = self) def updatePages(qprinter): self.scoreScene.printScore(qprinter, self.scoreView) dialog.paintRequested.connect(updatePages) dialog.exec_()
def __init__(self): QObject.__init__(self) self.regex = Regex() self.title = '' self.webView = QWebView() self.webView.settings().setAttribute(QWebSettings.AutoLoadImages, True) self.webView.settings().setAttribute(QWebSettings.JavascriptEnabled, True) self.webView.settings().setAttribute(QWebSettings.PluginsEnabled, True) self.webView.settings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True) self.pdfPrinter = QPrinter() self.webView.loadFinished.connect(self.convertToPdf)
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 __saveAsPDF(self, fileName): " Saves the flowchart as an PDF file " printer = QPrinter() printer.setOutputFormat(QPrinter.PdfFormat) printer.setPaperSize(QSizeF(self.scene.width(), self.scene.height()), QPrinter.Point) printer.setFullPage(True) printer.setOutputFileName(fileName) painter = QPainter(printer) self.scene.render(painter) painter.end() return
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 plotSVG(self, width, height, output_file, _plotting_object = None): """Plots the data specified in the current input file as a page in a PDF file with the given width and height, writing the output to the specified output file. Returns the SVG object produced.""" printer = QPrinter() svg = QSvgGenerator() svg.setFileName(output_file) svg.setSize(QSize(width, height)) svg.setViewBox(QRect(0, 0, width, height)) svg.setResolution(printer.resolution()) return self._plot(width, height, svg, _plotting_object)[0]
def on_actionPrint_triggered(self): if self._printer is None: self._printer = QPrinter() self._printer = QPrinter(QPrinterInfo(self._printer), QPrinter.HighResolution) self._printer.setPaperSize(self._getPaperSize()) dialog = QPrintPreviewDialog(self._printer, parent=self) def updatePages(qprinter): self.scoreScene.printScore(qprinter, self.scoreView) dialog.paintRequested.connect(updatePages) dialog.exec_()
class WebKitPDF ( QObject ): def __init__ ( self, url, dest ): QObject.__init__ ( self ) self.dest = dest self.page = QtWebKit.QWebPage ( self ) self.mainFrame = self.page.mainFrame() self.mainFrame.load ( QUrl ( url ) ) # Settings # Disable the scrollbars self.mainFrame.setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff) self.mainFrame.setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff) self.connect ( self.page, SIGNAL ( "loadProgress(int)" ), self.loadProgress ) self.connect ( self.page, SIGNAL ( "loadFinished(bool)" ), self.renderPDF ) def loadProgress ( self, progress ): print "Progress: ", progress def renderPDF ( self, status ): print "Load finished with status: ", status print "Rendering PDF ..." contentsSize = self.mainFrame.contentsSize() contentsSize.setWidth(1280) self.page.setViewportSize ( contentsSize ) self.printer = QPrinter ( QPrinter.PrinterResolution ) #self.printer = QPrinter ( QPrinter.ScreenResolution ) self.printer.setOutputFormat ( QPrinter.PdfFormat ) #self.printer.setPaperSize ( QPrinter.A4 ) self.printer.setFullPage( True ) self.printer.setPaperSize ( QSizeF( contentsSize ), QPrinter.DevicePixel ) self.printer.setOrientation ( QPrinter.Portrait ) self.printer.setOutputFileName ( self.dest ) self.painter = QPainter ( self.printer ) self.painter.setRenderHint ( QPainter.Antialiasing ) self.mainFrame.render ( self.painter ) self.painter.end() app = QtGui.QApplication.instance() app.exit ( 0 )
def printWindow(self, printer=None): if not printer: printer = QPrinter() printer.setFullPage(True) printer.setPageSize(QPrinter.A4) dialog = QPrintDialog(printer, self) dialog.setWindowTitle(QCoreApplication.translate('Graphics', 'Print Document')) if dialog.exec_() != QDialog.Accepted: return # FIXME: on windows the resolutions seems to be very low, why? #printer.setResolution(600) painter = QPainter(printer) painter.setRenderHint(QPainter.Antialiasing) self.graphicsView.scene().render(painter)
def save_report(self): """Save report""" filename = QFileDialog.getSaveFileName( self, "Save Report", self.save_dir, "HTML (*.html);;PDF (*.pdf);;Report (*.report)") if not filename: return QDialog.Rejected self.save_dir = os.path.dirname(filename) self.saveSettings() _, extension = os.path.splitext(filename) if extension == ".pdf": printer = QPrinter() printer.setPageSize(QPrinter.A4) printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(filename) self.report_view.print_(printer) elif extension == ".report": self.save(filename) else: frame = self.report_view.page().currentFrame() with open(filename, "w", encoding="utf-8") as f: f.write(frame.documentElement().toInnerXml()) self.report_changed = False return QDialog.Accepted
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 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 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 init_print(self, linenos=True, style="default"): app = QApplication(sys.argv) # noqa doc = QTextDocument() doc.setHtml(self.highlight_file(linenos=linenos, style=style)) printer = QPrinter() printer.setOutputFileName(self.pdf_file) printer.setOutputFormat(QPrinter.PdfFormat) page_size_dict = { "a2": QPrinter.A2, "a3": QPrinter.A3, "a4": QPrinter.A4 } printer.setPageSize(page_size_dict.get(self.size.lower(), QPrinter.A4)) printer.setPageMargins(15, 15, 15, 15, QPrinter.Millimeter) doc.print_(printer) logging.info("PDF created at %s" % (self.pdf_file))
def _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 __saveAsPDF( self, fileName ): " Saves the flowchart as an PDF file " printer = QPrinter() printer.setOutputFormat( QPrinter.PdfFormat ) printer.setPaperSize( QSizeF( self.scene.width(), self.scene.height() ), QPrinter.Point ) printer.setFullPage( True ) printer.setOutputFileName( fileName ) painter = QPainter( printer ) self.scene.render( painter ) painter.end() return
def __init__(self, parent): QFrame.__init__(self,parent) self.filename = QString() self.copiedItem = QByteArray() self.pasteOffset = 5 self.prevPoint = QPoint() self.addOffset = 5 self.screenSize = (320, 240) self.bgColor = QColor(244,244,244) '''0.Portrait 1.Landscape''' self.orientation = 0 self.currentItem = None self.printer = QPrinter(QPrinter.HighResolution) self.printer.setPageSize(QPrinter.Letter) '''Header''' self.headingBar = HeadingBar(self) '''WidgetsBar''' self.widgetsBar = WidgetsBar(self) '''Property''' self.propertyBar = PropertyBar(self) '''view''' viewLayoutWidget = QFrame() viewLayoutWidget.setFrameShape(QFrame.StyledPanel) viewLayout = QHBoxLayout(viewLayoutWidget) #viewLayout.setMargin(10) self.view = ScreenView(viewLayoutWidget) '''scene''' self.scene = QGraphicsScene(self) #self.scene.selectionChanged.connect(self.setConnect) #self.view.setStyleSheet("border: 1px solid red;") self.setBackgroundColor(self.bgColor) self.setScreenSize(self.screenSize) self.view.setScene(self.scene) self.view.setAlignment(Qt.AlignCenter) self.connect(self.view, SIGNAL("dropped"),self.addPixmapFile) self.scroll_off = 1 self.setScrollBar() viewLayout.setMargin(0) viewLayout.addWidget(self.view) self.wrapped = [] # Needed to keep wrappers alive layout = QVBoxLayout(self) layout.addWidget(self.headingBar) layout.addWidget(viewLayoutWidget) layout.addWidget(self.widgetsBar) layout.addWidget(self.propertyBar) layout.setMargin(0) self.setLayout(layout)
def __outPDF(self): """ To save the profile as pdf file """ fileName = QFileDialog.getSaveFileName( self.__iface.mainWindow(), QCoreApplication.translate("VDLTools", "Save As"), QCoreApplication.translate("VDLTools", "Profile.pdf"),"Portable Document Format (*.pdf)") if fileName is not None: if self.__lib == 'Qwt5': printer = QPrinter() printer.setCreator(QCoreApplication.translate("VDLTools", "QGIS Profile Plugin")) printer.setOutputFileName(fileName) printer.setOutputFormat(QPrinter.PdfFormat) printer.setOrientation(QPrinter.Landscape) self.__plotWdg.print_(printer) elif self.__lib == 'Matplotlib': self.__plotWdg.figure.savefig(str(fileName))
def printer(self): if self._printer is None: self._printer = QPrinter(QPrinter.HighResolution) self._printer.setOrientation(QtGui.QPrinter.Landscape) self._printer.setFullPage(True) #self.translate(-15, -15) self._printer.setDocName(self.ganttWidget.ganttModel.name) return self._printer
def getPDFPrinter(self, name): printer = QPrinter(QPrinter.HighResolution) path = QFileDialog.getSaveFileName( None, None, os.path.join( self.settings.value("save path", os.path.expanduser("~")), # default folder name + ".pdf" # default filename ), "PDF (*.pdf)" ) if path is not None and path != "": self.settings.setValue("save path", os.path.dirname(path)) printer.setOutputFileName(path) return printer else: return None
def imprimir(self): print('Prepandando impresion') self.printer = QPrinter(QPrinter.HighResolution); self.printer.setPageSize(QPrinter.A4); self.printer.setOrientation(QPrinter.Portrait); self.printer.setPageMargins(10, 10, 10, 10, QPrinter.Millimeter) self.navegador.print_(self.printer)
def printMail(self): printer = QPrinter(mode=QPrinter.HighResolution) printer.setCreator("Daaq Mail") title = 'Daaq Mail' #title = validateFileName(title) printer.setDocName(title) printer.setOutputFileName(DOC_DIR + title + ".pdf") print_dialog = QPrintPreviewDialog(printer, self) print_dialog.paintRequested.connect(self.textViewer.print_) print_dialog.exec_()
def writePdf(dir_): newbody = originHTML.format(**htmlpara) printer = QPrinter() printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(dir_ + '.pdf') printer.setPageSize(QPrinter.A4) text = QTextDocument() text.setHtml(newbody.decode('utf-8')) text.print_(printer)
def init_print(self, linenos=True, style="default"): app = QApplication(sys.argv) # noqa doc = QTextDocument() doc.setHtml( self.highlight_file(linenos=linenos, style=style) ) printer = QPrinter() printer.setOutputFileName(self.pdf_file) printer.setOutputFormat(QPrinter.PdfFormat) page_size_dict = {"a2": QPrinter.A2, "a3": QPrinter.A3, "a4": QPrinter.A4} printer.setPageSize(page_size_dict.get(self.size.lower(), QPrinter.A4)) printer.setPageMargins(15, 15, 15, 15, QPrinter.Millimeter) doc.print_(printer) logging.info("PDF created at %s" % (self.pdf_file))
def save_report(self): """Save report""" filename = QFileDialog.getSaveFileName( self, "Save Report", self.save_dir, "HTML (*.html);;PDF (*.pdf);;Report (*.report)") if not filename: return QDialog.Rejected self.save_dir = os.path.dirname(filename) self.saveSettings() _, extension = os.path.splitext(filename) if extension == ".pdf": printer = QPrinter() printer.setPageSize(QPrinter.A4) printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(filename) self.report_view.print_(printer) elif extension == ".report": with open(filename, 'wb') as f: pickle.dump(self, f) else: frame = self.report_view.page().currentFrame() with open(filename, "w") as f: f.write(frame.documentElement().toInnerXml()) self.report_changed = False return QDialog.Accepted
def outPDF(self, iface, wdg, mdl, library): for i in range(0, mdl.rowCount()): if mdl.item(i, 0).data(Qt.CheckStateRole): name = str(mdl.item(i, 2).data(Qt.EditRole)) break fileName = QFileDialog.getSaveFileName( iface.mainWindow(), "Save As", "Profile of " + name + ".pdf", "Portable Document Format (*.pdf)") if fileName: if library == "Qwt5" and has_qwt: printer = QPrinter() printer.setCreator('QGIS Profile Plugin') printer.setOutputFileName(fileName) printer.setOutputFormat(QPrinter.PdfFormat) printer.setOrientation(QPrinter.Landscape) wdg.plotWdg.print_(printer) elif library == "Matplotlib" and has_mpl: wdg.plotWdg.figure.savefig(str(fileName))
def makeTableDocument(self): printer = QPrinter() document = QTextDocument() document.setDefaultStyleSheet("table {border:1px; border-color:teal}") document.setDefaultStyleSheet("h1, h2, h3 {color:teal}") document.setDocumentMargin(0.0) document.setPageSize(QSizeF(printer.pageRect().size())) header = ''' <html> <body> <div style="line-height:2.5"> <h1>Desmond International College</h1> <h2>Km4, Happiness Street, Kafanchan</h2> <h2>Kaduna, Nigeria</h2> </div> <div> <h2 style='display:block; text-align:center; word-spacing:10vw; text-transform: uppercase; margin-top:25px; margin-bottom:15px'><u>STUDENT DATA TABLE</u></h2> </div> </body> </html> ''' #print(dir(document)) cursor = QTextCursor(document) rows = self.table.rowCount() columns = self.table.columnCount() cursor.insertHtml(header) table = cursor.insertTable(rows + 1, columns) formats = table.format() formats.setHeaderRowCount(1) table.setFormat(formats) formats = cursor.blockCharFormat() formats.setFontWeight(QFont.Bold) for column in range(columns): cursor.setCharFormat(formats) cursor.insertText(self.table.horizontalHeaderItem(column).text()) cursor.movePosition(QTextCursor.NextCell) for row in range(rows): for column in range(columns): cursor.insertText(self.table.item(row, column).text()) cursor.movePosition(QTextCursor.NextCell) return document
def print_pdf(html, filename): """ Print HTML to PDF. """ wv = QWebView() wv.setHtml(html) # doc = QTextDocument() # doc.setHtml(html) printer = QPrinter() printer.setOutputFileName(filename) printer.setOutputFormat(QPrinter.PdfFormat) printer.setPageSize(QPrinter.A4) printer.setPageMargins(15, 15, 15, 15, QPrinter.Millimeter) # doc.print_(printer) wv.print_(printer) print("PDF Generated: " + filename)
def __init__(self, parent=None, fakeStartup=False, filename=None): ''' Constructor ''' self._fakeStartup = fakeStartup super(DrumBurp, self).__init__(parent) self._state = None self._asciiSettings = None self._printer = None self.setupUi(self) self.scoreScene = None self.paperBox.blockSignals(True) self.paperBox.clear() self._knownPageHeights = [] printer = QPrinter() printer.setOutputFileName("invalid.pdf") for name in dir(QPrinter): attr = getattr(QPrinter, name) if (isinstance(attr, QPrinter.PageSize) and name != "Custom"): self.paperBox.addItem(name) printer.setPaperSize(attr) self._knownPageHeights.append(printer.pageRect().height()) self._pageHeight = printer.paperRect().height() self.paperBox.blockSignals(False) settings = self._makeQSettings() self.recentFiles = [ unicode(fname) for fname in settings.value("RecentFiles").toStringList() if os.path.exists(unicode(fname)) ] if filename is None: filename = (None if len(self.recentFiles) == 0 else self.recentFiles[0]) self.filename = filename self.addToRecentFiles() self.updateRecentFiles() self.songProperties = QDisplayProperties() # Create scene self.scoreScene = QScore(self) self.restoreGeometry(settings.value("Geometry").toByteArray()) self.restoreState(settings.value("MainWindow/State").toByteArray()) self.statusbar.addPermanentWidget(QFrame()) self.availableNotesLabel = QLabel() self.availableNotesLabel.setMinimumWidth(250) self.statusbar.addPermanentWidget(self.availableNotesLabel) self._infoBar = QLabel() self.statusbar.addPermanentWidget(self._infoBar) self._initializeState() self.setSections() QTimer.singleShot(0, self._startUp) self.actionCheckOnStartup.setChecked( settings.value("CheckOnStartup").toBool())
def __init__(self, *args, **kwargs): BasePrinter.__init__(self, *args, **kwargs) self.page_number = 0 self.printer = QPrinter(QPrinter.HighResolution) ## todo: remove-me self.printer.setOutputFileName("ufwi_log-page.pdf") self.printer.setOutputFormat(QPrinter.NativeFormat) #self.printer.setOrientation(QPrinter.Landscape) self.printer.setPaperSize(QPrinter.A4) self.printer.setResolution(100)
def print_pdf(html, destination): app = QApplication(sys.argv) web = QWebView() web.setHtml(html) printer = QPrinter() printer.setPageSize(QPrinter.A4) printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(destination) web.print_(printer) app.exit()
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 open_html_in_print_preview_from_gui_thread(html, html_document=QTextDocument, page_size=None, page_orientation=None): printer = QPrinter() printer.setPageSize(page_size or QPrinter.A4) printer.setOrientation(page_orientation or QPrinter.Portrait) dialog = QPrintPreviewDialog(printer) @QtCore.pyqtSlot(QPrinter) def render(printer): doc = html_document() doc.setHtml(html) doc.print_(printer) dialog.paintRequested.connect(render) # show maximized seems to trigger a bug in qt which scrolls the page down #dialog.showMaximized() desktop = QCoreApplication.instance().desktop() # use the size of the desktop instead to set the dialog size dialog.resize(desktop.width() * 0.75, desktop.height() * 0.75) dialog.exec_()
def writePdf(dir_): newbody = originHTML.format(**htmlpara) printer = QPrinter() printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(dir_+'.pdf') printer.setPageSize(QPrinter.A4) text = QTextDocument() text.setHtml(newbody.decode('utf-8')) text.print_(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 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 preview(self): """ Muestra el dialogo de vista previa de impresión """ try: printer = QPrinter() printer.setOrientation(self.orientation) printer.setPageSize(self.pageSize) web = self.web + self.printIdentifier report = reports.frmReportes(web, printer, self) report.exec_() except NotImplementedError as inst: QMessageBox.information( self, qApp.organizationName(), u"No se ha implementado la función de impresión para este modulo" ) logging.error(unicode(inst)) except UserWarning as inst: QMessageBox.critical(self, qApp.organizationName(), unicode(inst)) logging.error(unicode(inst)) except Exception as inst: QMessageBox.critical(self, qApp.organizationName(), "Hubo un error al intentar mostrar su reporte") logging.critical(unicode(inst))
def __init__(self, parent = None, fakeStartup = False, filename = None): ''' Constructor ''' self._fakeStartup = fakeStartup super(DrumBurp, self).__init__(parent) self._state = None self._asciiSettings = None self._printer = None self.setupUi(self) self.scoreScene = None self.paperBox.blockSignals(True) self.paperBox.clear() self._knownPageHeights = [] printer = QPrinter() printer.setOutputFileName("invalid.pdf") for name in dir(QPrinter): attr = getattr(QPrinter, name) if (isinstance(attr, QPrinter.PageSize) and name != "Custom"): self.paperBox.addItem(name) printer.setPaperSize(attr) self._knownPageHeights.append(printer.pageRect().height()) self._pageHeight = printer.paperRect().height() self.paperBox.blockSignals(False) settings = self._makeQSettings() self.recentFiles = [unicode(fname) for fname in settings.value("RecentFiles").toStringList() if os.path.exists(unicode(fname))] if filename is None: filename = (None if len(self.recentFiles) == 0 else self.recentFiles[0]) self.filename = filename self.addToRecentFiles() self.updateRecentFiles() self.songProperties = QDisplayProperties() # Create scene self.scoreScene = QScore(self) self.restoreGeometry(settings.value("Geometry").toByteArray()) self.restoreState(settings.value("MainWindow/State").toByteArray()) self.statusbar.addPermanentWidget(QFrame()) self.availableNotesLabel = QLabel() self.availableNotesLabel.setMinimumWidth(250) self.statusbar.addPermanentWidget(self.availableNotesLabel) self._infoBar = QLabel() self.statusbar.addPermanentWidget(self._infoBar) self._initializeState() self.setSections() QTimer.singleShot(0, self._startUp) self.actionCheckOnStartup.setChecked(settings.value("CheckOnStartup").toBool())
def filePrint(self): if self.image.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.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 on_actionExportPDF_triggered(self): try: printer = QPrinter(mode = QPrinter.HighResolution) printer.setPaperSize(self._getPaperSize()) printer.setOutputFormat(QPrinter.PdfFormat) if self.filename: outfileName = list(os.path.splitext(self.filename)[:-1]) outfileName = os.extsep.join(outfileName + ["pdf"]) else: outfileName = "Untitled.pdf" printer.setOutputFileName(outfileName) printer.setPaperSize(self._getPaperSize()) dialog = QPrintPreviewDialog(printer, parent = self) def updatePages(qprinter): self.scoreScene.printScore(qprinter, self.scoreView) dialog.paintRequested.connect(updatePages) dialog.exec_() self.updateStatus("Exported to PDF %s" % outfileName) except StandardError: QMessageBox.warning(self.parent(), "Export failed!", "Could not export PDF to " + outfileName)
def writePdfabs(dir_): updates = PDF_PARAMETER htmlpara.update(updates) newbody = originHTML.format(**htmlpara) # with open('t.html', 'wb') as f: # f.write(newbody) # f.close() printer = QPrinter() printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(dir_) printer.setPageSize(QPrinter.A4) text = QTextDocument() text.setHtml(newbody.decode('utf-8')) text.print_(printer)
def __init__(self, parent, own_toolbar=False): """ @param parent: El widget padre de esta ventana @param own_toolbar: Si este widget dibujara su toolbar en el padre o en el mismo @type parent: QWidget @type own_toolbar: bool """ super(Base, self).__init__(parent) self.user = user.LoggedUser self._status = True self.parentWindow = parent self.own_toolbar = own_toolbar self.database = QSqlDatabase.database() """ @type: QSqlDatabase @ivar: La base de datos a la cual se conecta el sistema """ self.mapper = QDataWidgetMapper(self) u""" @type: QDataWidgetMapper @ivar: El mapper que se encarga de asignar los datos del modelo de navegación a los distintos widgets """ self.printProgressBar = QProgressBar(self) self.webview = QWebView() """ @ivar: EL objeto webview usado para cargar los reportes @type: QWebView """ self.loaded = False """ @ivar: Si se pudo o no cargar un reporte @type: bool """ self.startUi() self.editmodel = None self.printer = QPrinter() self._status = False