def saveReport(self, filename): directory = os.path.dirname(filename) if not os.path.isdir(directory): os.makedirs(directory) printer = QPrinter() printer.setOutputFormat(QPrinter.PdfFormat) printer.setOrientation(QPrinter.Landscape) printer.setPageSize(QPrinter.A4) printer.setOutputFileName(filename) if filename: self.print_(printer)
def actionPrint(self): """打印报告""" printer = QPrinter() printer.setOutputFormat(QPrinter.NativeFormat) printer.setOutputFileName("") printer.setOrientation(QPrinter.Landscape) printer.setPageSize(QPrinter.A4) #=======================================================# #无需选择 printDialog = QPrintDialog(printer, self) #self.print_(printer) #如果需要选择打印机 if printDialog.exec_(): self.print_(printer)
def printIndex(self): widget = QApplication.focusWidget() if self.state.printer is None: self.state.printer = QPrinter(QPrinter.HighResolution) self.state.printer.setColorMode(QPrinter.GrayScale) settings = QSettings() size = PaperSizeKind( int(settings.value(Gopt.Key.PaperSize, Gopt.Default.PaperSize))) self.state.printer.setPaperSize( QPrinter.Letter if size is PaperSizeKind.LETTER else QPrinter. A4) with Lib.Qt.DisableUI(*self.window.widgets(), forModalDialog=True): form = QPrintDialog(self.state.printer, self.state.window) form.setWindowTitle("Print Index") if form.exec_(): try: with Lib.DisableUI(*self.window.widgets()): config = self.state.model.configs().copy() config.Filename = "print.$$$" config.Printer = self.state.printer Output.outputEntries(self.state.model, config, "Printing", self.window.reportProgress) say("Printed") except Output.Error as err: say("Failed to print: {}".format(err)) logging.error("printIndex failed: {}".format(err)) Lib.restoreFocus(widget)
def saveAsPDF(self): '''Save plot as a PDF''' if not self.control.hasPlot: error.showMessage('Cannot save.. there is no data to save yet') return filter = 'PDF Documents (*.pdf);;All (*)' d = '' if self.pdfName is None else self.pdfName s = QFileDialog.getSaveFileName(self, 'PDF File Name', d, filter) # Continue unless the user hit cancel if not s[0]: return self.pdfName = s[0] # Set up the PDF printer printer = QPrinter() printer.setOutputFormat(QPrinter.PdfFormat) printer.setOrientation(QPrinter.Landscape) printer.setOutputFileName(self.pdfName) printer.setCreator('RAPID') # Send to the plot for printing p = QPainter() p.begin(printer) x, y = self.plot.calculatedData() plt = pgplot(x, y, antialias=True, connect='all', pen={'color': 'b', 'width': 0}) plt.setLabel('bottom', "Frequency (Wavenumbers, cm<sup>-1</sup>)") plt.getAxis('bottom').setPen('k') plt.setLabel('left', "Intensity (Normalized)") plt.getAxis('left').setPen('k') plt.setYRange(0, 1.1, padding=0) plt.invertX(self.plot.reversed) plt.setBackground('w') # White # The raw (experimental) data, if any if self.plot.rawData is not None: data = self.plot.getRawData() x, y = data[:,0], data[:,1] curve2 = PlotCurveItem(x, y, antialias=True, connect='all', pen={'color': 'g', 'width': 0}) plt.addItem(curve2) plt.render(p) p.end()
def OnPrint(self): """""" document = self.document() printer = QPrinter() dlg = QPrintDialog(printer, self) if dlg.exec_() != QDialog.Accepted: return document.print_(printer)
def print_(self): canvas = self.mw.get_current_canvas() if not canvas: return printer = QPrinter() dlg = QPrintDialog(printer, self.mw) if dlg.exec_() == QDialog.Accepted: painter = QPainter(printer) painter.drawImage(0, 0, canvas.image) painter.end()
def convert_html_to_pdf(source, destination, page_size=QPrinter.Letter, print_format=QPrinter.PdfFormat, timeout=10000, app=None): """Converts an .html file at the source to a .pdf at the destination Any external files linked in the source file must be paths relative to the location of the source file itself. If building the html file dynamically, the rel_path function can be used to create proper relative paths using the .html location as the source location. The conversion is done using th ability of a QPrinter to print a QWebView to a PDF. This means we must have some Qt bindings, either PySide (default) or PyQt4 (5 support incoming?), but then are only limited by what the QWebView can display. While the intent is so print to a PDF, the format parameter is exposed so that this can be used to print directly to a printer or (if >=Qt4.2) PostScript format. If this is being used in a larger QApplication, we should only have one instance of QApplication, so pass the existing instance to the `app` parameter. """ if app is None: app = QApplication(sys.argv) view = QWebView() # We want to ensure the page was fully loaded before printing, so # we wait for the loadFinished event to fire. with wait_for_signal(view.loadFinished, timeout=timeout): # QUrl requires absolute path names view.load(QUrl.fromLocalFile(os.path.abspath(source))) # With the QWebView loaded, we now print to the destination PDF printer = QPrinter() printer.setPageSize(page_size) printer.setOutputFormat(print_format) printer.setOutputFileName(destination) view.print_(printer) # Exit the application app.exit()
def convert_html_to_pdf( source, destination, page_size=QPrinter.Letter, print_format=QPrinter.PdfFormat, timeout=10000, app=None): """Converts an .html file at the source to a .pdf at the destination Any external files linked in the source file must be paths relative to the location of the source file itself. If building the html file dynamically, the rel_path function can be used to create proper relative paths using the .html location as the source location. The conversion is done using th ability of a QPrinter to print a QWebView to a PDF. This means we must have some Qt bindings, either PySide (default) or PyQt4 (5 support incoming?), but then are only limited by what the QWebView can display. While the intent is so print to a PDF, the format parameter is exposed so that this can be used to print directly to a printer or (if >=Qt4.2) PostScript format. If this is being used in a larger QApplication, we should only have one instance of QApplication, so pass the existing instance to the `app` parameter. """ if app is None: app = QApplication(sys.argv) view = QWebView() # We want to ensure the page was fully loaded before printing, so # we wait for the loadFinished event to fire. with wait_for_signal(view.loadFinished, timeout=timeout): # QUrl requires absolute path names view.load(QUrl.fromLocalFile(os.path.abspath(source))) # With the QWebView loaded, we now print to the destination PDF printer = QPrinter() printer.setPageSize(page_size) printer.setOutputFormat(print_format) printer.setOutputFileName(destination) view.print_(printer) # Exit the application app.exit()
def __init__(self, mainwindow, settings=None): """ Initializes the text editor widget. """ super(TextEditor, self).__init__(mainwindow) self.setupUi(self.mw) self.plainTextEdit.clear() self.plainTextEdit.setEnabled(False) self.plainTextEdit.show() self.highlighter = SyntaxHighlighter(self.plainTextEdit.document(), settings) self.initAutocomplete() self._initNumberBar() self.hidden = {} self.printer = QPrinter(QPrinterInfo.defaultPrinter()) self.plainTextEdit.setTextCursor( self.plainTextEdit.cursorForPosition(QPoint(0, 0))) self.canUndo = False self.canRedo = False self.ontologySelector.setCurrentIndex(-1) self.timer = QTimer(self) self.timer.setSingleShot(True) self.timer.timeout.connect(self.commit) #Connects self.getWidget().textChanged.connect(self.searchCompletion) self.plainTextEdit.undoAvailable.connect(self.setCanUndo) self.plainTextEdit.redoAvailable.connect(self.setCanRedo) self.ontologySelector.currentIndexChanged[int].connect( self.showOtherOntology) self.plainTextEdit.textChanged.connect(self.expandIfBracketRemoved) self.plainTextEdit.textChanged.connect(self.setTextChanged) self._updateOntologySelector() #must be after connects
def print_to_pdf(self, path, paper_size=(8.5, 11.0), paper_margins=(0, 0, 0, 0), paper_units=QPrinter.Inch, zoom_factor=1.0): """Saves page as a pdf file. See qt4 QPrinter documentation for more detailed explanations of options. :param path: The destination path. :param paper_size: A 2-tuple indicating size of page to print to. :param paper_margins: A 4-tuple indicating size of each margin. :param paper_units: Units for pager_size, pager_margins. :param zoom_factor: Scale the output content. """ assert len(paper_size) == 2 assert len(paper_margins) == 4 printer = QPrinter(mode=QPrinter.ScreenResolution) printer.setOutputFormat(QPrinter.PdfFormat) printer.setPaperSize(QtCore.QSizeF(*paper_size), paper_units) printer.setPageMargins(*(paper_margins + (paper_units, ))) printer.setFullPage(True) printer.setOutputFileName(path) if self.webview is None: self.webview = QtWebKit.QWebView() self.webview.setPage(self.page) self.webview.setZoomFactor(zoom_factor) self.webview.print_(printer)
def capture_pdf(self): printer = QPrinter(QPrinter.HighResolution) printer.setResolution(300) printer.setOutputFileName("QtPrinter.pdf") printer.setPaperSize(QPrinter.A4) printer.setOrientation(QPrinter.Landscape) printer.setOutputFormat(QPrinter.PdfFormat) painter = QPainter(printer) self.main_frame.render(painter) painter.end()
def print_to_pdf(self, path, paper_size=(8.5, 11.0), paper_margins=(0, 0, 0, 0), paper_units=QPrinter.Inch, zoom_factor=1.0): """Saves page as a pdf file. See qt4 QPrinter documentation for more detailed explanations of options. :param path: The destination path. :param paper_size: A 2-tuple indicating size of page to print to. :param paper_margins: A 4-tuple indicating size of each margin. :param paper_units: Units for pager_size, pager_margins. :param zoom_factor: Scale the output content. """ assert len(paper_size) == 2 assert len(paper_margins) == 4 printer = QPrinter(mode=QPrinter.ScreenResolution) printer.setOutputFormat(QPrinter.PdfFormat) printer.setPaperSize(QtCore.QSizeF(*paper_size), paper_units) printer.setPageMargins(*(paper_margins + (paper_units,))) printer.setFullPage(True) printer.setOutputFileName(path) if self.webview is None: self.webview = QtWebKit.QWebView() self.webview.setPage(self.page) self.webview.setZoomFactor(zoom_factor) self.webview.print_(printer)
def testQPrinterGetPageMargins(self): # Bug #742 obj = QPrinter() values = (10.0, 20.0, 30.0, 40.0, QPrinter.Point) obj.setPageMargins(*values) self.assert_(self.compareTuples(obj.getPageMargins(QPrinter.Point), values[:-1]))
def saveAsPdf(self, fn, force=False): """ Save bar image as a eps file. Args: fn: Filename force: if True, overwrites an existing file. If false, raises a RuntimeError if file already exists. """ printer = QPrinter(QPrinter.HighResolution) printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(fn) printer.setFullPage(True) printer.setPageSize(QPrinter.Custom) printer.setPaperSize(QSizeF(*self.size), QPrinter.Millimeter) printer.setPageMargins(0, 0, 0, 0, QPrinter.Millimeter) painter = QPainter(printer) painter.setRenderHint(QPainter.Antialiasing) painter.setBrush(Qt.white) painter.setPen(Qt.white) painter.drawRect(QRect(0, 0, *self.size)) targetrect = QRectF(0, 0, printer.width(), printer.height()) sourcerect = QRectF(0, 0, *self.size) self.render(painter, targetrect, sourcerect) painter.end() return True
def print_(self): """Print note with preview""" printer = QPrinter() dialog = QPrintPreviewDialog(printer) dialog.paintRequested.connect(self.page.view().print_) dialog.exec_()
def output(config, document): p = ( """<p style="font-family: '{family}'; font-size: {size}pt;">""".format( family=config.StdFont, size=config.StdFontSize)) pad = lambda match: p + (int(match.group("level")) * 4 * " ") doc = QTextDocument() doc.setHtml(INDENT_RX.sub(pad, document)) printer = getattr(config, "Printer", None) if printer is None: printer = QPrinter(QPrinter.HighResolution) printer.setCreator("{} {}".format(QApplication.applicationName(), QApplication.applicationVersion())) printer.setOutputFormat(QPrinter.PdfFormat) printer.setOrientation(QPrinter.Portrait) settings = QSettings() size = PaperSizeKind( int(settings.value(Gopt.Key.PaperSize, Gopt.Default.PaperSize))) printer.setPaperSize( QPrinter.A4 if size is PaperSizeKind.A4 else QPrinter.Letter) printer.setOutputFileName(config.Filename) doc.print_(printer)
def __init__(self): self.pages = [] self.handler = QPrinter()
class Printer(object): def __init__(self): self.pages = [] self.handler = QPrinter() def reset(self): self.pages = [] def make_page(self, html): page = QTextDocument() page.setHtml(html) self.pages.append(page) def generate_employee_table(self, employees): html = """ <table align="center" cellpadding="10"> <tr> <th>ID</th> <th>Name</th> <th>Address</th> <th>Phone Number</th> <th>Cell Number</th> <th>Email Address</th> </tr> """ for employee in employees: html += """ <tr> <td>%(id)s</td> <td>%(first_name)s %(last_name)s</td> <td>%(street_address)s<br /> %(city)s %(state)s %(zip_code)s</td> <td>%(phone_number)s</td> <td>%(cell_number)s</td> <td>%(email_address)s</td> </tr> """ % employee html += "</table>" return html def generate_employer_table(self, employer): html = """ <table align="center" width="500"> <tr> <th>ID</th> <td>%(id)s</td> </tr> <tr> <th></th> <td></td> </tr> <tr> <th>Company</th> <td>%(name)s</td> </tr> <tr> <th>Address</th> <td> %(street_address)s<br /> %(city)s %(state)s %(zip_code)s </td> </tr> <tr> <th></th> <td></td> </tr> <tr> <th>Contact Person</th> <td>%(contact_person)s</td> </tr> <tr> <th></th> <td></td> </tr> <tr> <th>Phone Number</th> <td>%(phone_number)s</td> </tr> <tr> <th></th> <td></td> </tr> <tr> <th>Email Address</th> <td>%(email_address)s</td> </tr> </table><br> """ % employer return html def generate_sorted_employee_table(self, employees): html = """ <table align="center" cellspacing="10"> <tr> <th>Overall Score</th> <th>ID</th> <th>Employee</th> <th>Site</th> <th>Overall Comments</th> </tr> """ for employer, employee, score, comments in employees: html += """ <tr> <td>%s</td> <td>%s</td> <td> %s %s<br /> %s<br /> %s %s %s </td> <td>%s<br />(ID# %s)</td> <td>%s</td> </tr> """ % (score, employee["id"], employee["first_name"], employee["last_name"], employee["street_address"], employee["city"], employee["state"], employee["zip_code"], employer["name"], employer["id"], comments) html += "</table>" return html def emit_employer(self, employer, employees): html = """ <img style="float: left;" src=":/img/mmt.png" width="200" height="65"> <h1 align="right">Employer Information</h1> <hr /> <p> <b>CLIENT WORKSITE:</b><br /> %(name)s (ID# %(id)s)<br /> %(street_address)s<br /> %(city)s, %(state)s %(zip_code)s </p> <p> <b>CLIENT CONTACT:</b><br /> %(contact_person)s<br /> %(phone_number)s<br /> %(email_address)s </p> """ % employer if employees: html += '<h2 align="center">Employees</h2><hr />' html += self.generate_employee_table(employees) self.make_page(html) def emit_employee(self, employer, employee): html = """ <img style="float: left;" src=":/img/mmt.png" width="200" height="65" cellspacing=0 cellpadding=1> <h1 align="right">Employee Information</h1> <hr /> """ html += """ <table align="center" cellpadding="1" width="500"> <h2 align="left">Employee</h2> <tr> <th></th> <td></td> </tr> <tr> <th>ID</th> <td>%(id)s</td> </tr> <tr> <th></th> <td></td> </tr> <tr> <th>Name</th> <td>%(first_name)s %(last_name)s</td> </tr> <tr> <th></th> <td></td> </tr> <tr> <th>Address</th> <td> %(street_address)s<br /> %(city)s %(state)s %(zip_code)s </td> <tr/> <tr> <th></th> <td></td> </tr> <tr> <th>Email Address</th> <td>%(email_address)s</td> </tr> <tr> <th></th> <td></td> </tr> <tr> <th>Phone Number</th> <td>%(phone_number)s</td> </tr> <tr> <th></th> <td></td> </tr> <tr> <th>Cell Number</th> <td>%(cell_number)s</td> </tr> </table><br /> """ % employee html += '<h2 align="left">Employer</h2><br />' html += self.generate_employer_table(employer) self.make_page(html) def emit_evaluation(self, employer, employee, evaluation): eval_time = QDateTime() eval_time.setTime_t(int(evaluation["date"])) readable_evaluation = eval_time.date().toString("MM.dd.yyyy") next_eval_time = QDateTime() next_eval_time.setTime_t(int(evaluation["next_date"])) readable_next_evaluation = next_eval_time.date().toString("MM.dd.yyyy") recommend = ("Yes" if evaluation["recommended"] else "No") html = """ <img style="float: left;" src=":/img/mmt.png" width="200" height="65"> <h1 align="right"> Individual Employee Evaluation including Comments </h1> <hr /> <p> <b>Employee:</b><br /> %s %s (ID# %s)<br /> %s<br /> %s, %s %s<br /> %s </p> <p> <b>Employment Site:</b><br /> %s<br /> %s<br /> %s, %s, %s </p> <table align="center" width="500"> <tr> <th></th> <td></td> </tr> <tr> <td>Date Evaluated</td> <td>%s</td> </tr> <tr> <td>Next Evaluation Date</td> <td>%s</td> </tr> <tr> <th></th> <td></td> </tr> <tr> <td>Quality Score</td> <td>%s</td> </tr> <tr> <td>Quality Comments</td> <td>%s</td> </tr> <tr> <th></th> <td></td> </tr> <tr> <td>Habits Score</td> <td>%s</td> </tr> <tr> <td>Habits Comments</td> <td>%s</td> </tr> <tr> <th></th> <td></td> </tr> <tr> <td>Knowledge Score</td> <td>%s</td> </tr> <tr> <td>Knowledge Comments</td> <td>%s</td> </tr> <tr> <th></th> <td></td> </tr> <tr> <td>Behavior Score</td> <td>%s</td> </tr> <tr> <td>Behavior Comments</td> <td>%s</td> </tr> <tr> <th></th> <td></td> </tr> <tr> <td>Employee Score</td> <td>%s</td> </tr> <tr> <td>Overall Score</td> <td>%s</td> </tr> <tr> <th></th> <td></td> </tr> <tr> <td>Comments</td> <td>%s</td> </tr> <tr> <td>Recommended</td> <td>%s</td> </tr> </table> """ % (employee["first_name"], employee["last_name"], employee["id"], employee["street_address"], employee["city"], employee["state"], employee["zip_code"], employee["phone_number"], employer["name"], employer["street_address"], employer["city"], employer["state"], employer["zip_code"], readable_evaluation, readable_next_evaluation, evaluation["quality_score"], evaluation["quality_comments"], evaluation["habits_score"], evaluation["habits_comments"], evaluation["knowledge_score"], evaluation["knowledge_comments"], evaluation["behavior_score"], evaluation["behavior_comments"], evaluation["average_score"], evaluation["overall_score"], evaluation["comments"], recommend) self.make_page(html) def emit_tps_report(self, employees): html = """ <img style="float: left;" src=":/img/mmt.png" width="200" height="65"> <h1 align="right">TPS Report<br /> </h1> <hr /> """ html += self.generate_sorted_employee_table(employees) self.make_page(html) def emit_sorted_employees(self, employees): html = """ <img style="float: left;" src=":/img/mmt.png" width="200" height="65"> <h1 align="right">All Employees sorted by Evalation Score<br />(highest to lowest)</h1> <hr /> <table align="center" cellspacing="10"> <tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th>Email Address</th> <th>Phone Number</th> <th>Cell Number</th> <th>Overall Score</th> </tr> """ for employer, employee, score, comments in employees: html += """ <tr> <td>%s</td> <td>%s</td> <td>%s</td> <td>%s</td> <td>%s</td> <td>%s</td> <td>%s</td> </tr> """ % (employee["id"], employee["first_name"], employee["last_name"], employee["email_address"], employee["phone_number"], employee["cell_number"], score) html += "</table>" self.make_page(html) def paper_mode(self): self.handler.setOutputFormat(QPrinter.NativeFormat) self.handler.setOutputFileName("") def pdf_mode(self, file_name): self.handler.setOutputFormat(QPrinter.PdfFormat) self.handler.setOutputFileName(file_name) def run(self): page_num = 1 last_page = len(self.pages) self.painter = QPainter(self.handler) for page in self.pages: width = self.painter.viewport().width() height = self.painter.viewport().height() rect = QRect(0, 0, width, height) self.painter.save() self.painter.setViewport(rect) page.setTextWidth(width) page.drawContents(self.painter) self.painter.restore() if page_num != last_page: self.handler.newPage() page_num += 1 self.painter.end() self.reset()