def printing(printer, context): print("当前打印机:" + str(printer)) printerInfo = QPrinterInfo() p = QPrinter() for item in printerInfo.availablePrinters(): if printer == str(item.printerName()): p = QPrinter(item) doc = QTextDocument() doc.setDocumentMargin(0) print('physicalDpiX:' + str(p.physicalDpiX())) print('resolution:' + str(p.resolution())) print('height:' + str(p.height())) print('width:' + str(p.width())) scale = p.physicalDpiX() / p.resolution() print('scale:' + str(scale)) print('supportedResolutions:' + str(p.supportedResolutions())) print('logicalDpiX:' + str(p.logicalDpiX())) doc.setPageSize( QSizeF(p.logicalDpiX() * (p.width() / 25.4 / scale), p.logicalDpiY() * (p.height() / 25.4 / scale))) doc.setHtml(context) # new_p = QPrinter() print("开始打印") p.setOutputFormat(QPrinter.NativeFormat) doc.print_(p)
def printing(printer, context): p = QPrinter() doc = QTextDocument() htmlStr = context print('aaaa', htmlStr) doc.setHtml(htmlStr) doc.setPageSize(QSizeF(p.logicalDpiX() * (80 / 25.4), p.logicalDpiY() * (297 / 25.4))) p.setOutputFormat(QPrinter.NativeFormat) doc.print_(p) @staticmethod def printing_22(printer, context): printerInfo = QPrinterInfo() p = QPrinter() for item in printerInfo.availablePrinters(): if printer == item.printerName(): p = QPrinter(item) doc = QTextDocument() doc.setHtml(u'%s' % context) doc.setPageSize(QSizeF(p.logicalDpiX() * (80 / 25.4), p.logicalDpiY() * (297 / 25.4))) p.setOutputFormat(QPrinter.NativeFormat) doc.print_(p) if __name__ == '__main__': import sys from PyQt5.QtWidgets import QApplication app = QApplication(sys.argv) ########################################## html = '<html><head></head><body><h1>55555</h1><b>bold</b></body></html>' p = "defaultPrinter" # 打印机名称 # Printer.printing(p, html) # Printer.printerList() Printer.printing_22(p, html) ##################################################### sys.exit(app.exec_())
def printing(printer, context): printerInfo = QPrinterInfo() p = QPrinter() for item in printerInfo.availablePrinters(): if printer == item.printerName(): p = QPrinter(item) doc = QTextDocument() doc.setHtml(u'%s' % context) doc.setPageSize( QSizeF(p.logicalDpiX() * 32 / 25.4, p.logicalDpiY() * 16 / 25.4)) print(p.logicalDpiX()) print(p.logicalDpiY()) print(p.physicalDpiX()) print(p.physicalDpiY()) p.setOutputFormat(QPrinter.NativeFormat) doc.print_(p)
def printing(printer, context): p = QPrinter() doc = QTextDocument() htmlStr = context print('aaaa', htmlStr) doc.setHtml(htmlStr) doc.setPageSize( QSizeF(p.logicalDpiX() * (80 / 25.4), p.logicalDpiY() * (297 / 25.4))) p.setOutputFormat(QPrinter.NativeFormat) doc.print_(p)
def printing(printer, context, log): print("selected_printer:" + str(printer)) printerInfo = QPrinterInfo() p = QPrinter() for item in printerInfo.availablePrinters(): if printer == str(item.printerName()): p = QPrinter(item) try: doc = QTextDocument() doc.setDocumentMargin(0) log.write(Printer.getTime() + "--physicalDpiX --" + str(p.physicalDpiX()) + "\n") print('physicalDpiX:' + str(p.physicalDpiX())) print('resolution:' + str(p.resolution())) log.write(Printer.getTime() + "--resolution --" + str(p.resolution()) + "\n") print('height:' + str(p.height())) log.write(Printer.getTime() + "--height --" + str(p.height()) + "\n") print('width:' + str(p.width())) log.write(Printer.getTime() + "--width --" + str(p.width()) + "\n") scale = round(p.physicalDpiX() / p.resolution(), 4) print('scale:' + str(scale)) log.write(Printer.getTime() + "--scale --" + str(scale) + "\n") print('supportedResolutions:' + str(p.supportedResolutions())) log.write(Printer.getTime() + "--supportedResolutions --" + str(p.supportedResolutions()) + "\n") print('logicalDpiX:' + str(p.logicalDpiX())) log.write(Printer.getTime() + "--logicalDpiX --" + str(p.logicalDpiX()) + "\n") doc.setPageSize( QSizeF(p.logicalDpiX() * (p.width() / 25.4 / scale), p.logicalDpiY() * (p.height() / 25.4 / scale))) doc.setHtml(context) print("starting print") p.setOutputFormat(QPrinter.NativeFormat) doc.print_(p) except Exception as ee: print(ee) log.write(Printer.getTime() + "***print - error****" + str(ee) + "\n") log.close()
class Printer(QDialog): def __init__(self, parent=None): super(Printer, self).__init__(parent) self.printer = QPrinter() self.printer.setPageSize(QPrinter.Letter) self.setWindowTitle("Printing") 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 printReciept(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)) #A4 # document.setPageSize(QSizeF(self.printer.logicalDpiX() * (210 / 25.4),self.printer.logicalDpiY() * (297 / 25.4))); #小票 qsizeF = QSizeF(self.printer.logicalDpiX() * (257 / 25.4), self.printer.logicalDpiY() * (125 / 25.4)) # qsizeF = QSizeF(self.printer.logicalDpiX() * (215.90 / 25.4), self.printer.logicalDpiY() * (127.00 / 25.4)); # qsizeF = QSizeF(self.printer.logicalDpiY() * (125 / 25.4),self.printer.logicalDpiX() * (257 / 25.4)); self.printer.setPageSize(QPrinter.Custom) self.printer.setPaperName("小票2") paperSize = QSizeF(257, 125) self.printer.setPaperSize(paperSize, QPrinter.Millimeter) # self.printer.setPageSizeMM(qsizeF) document.setPageSize(qsizeF) # font = QFont(); # font.setPointSize(6) # document.setDefaultFont(font); document.setHtml(htmltext) document.print_(self.printer)
def printing_22(printer, context): printerInfo = QPrinterInfo() p = QPrinter() for item in printerInfo.availablePrinters(): if printer == str(item.printerName()): p = QPrinter(item) doc = QTextDocument() font = doc.defaultFont() font.setBold(True) font.setPointSize(font.pointSize() + 1) doc.setDefaultFont(font) font.setPixelSize(5) # doc.setPageSize(QSizeF(p.logicalDpiX() * (88 / 25.4), # p.logicalDpiY() * (297 / 25.4))) # x是间距,数字越小间距越大 y是纵长度 越大长度越小 doc.setPageSize(QSizeF(p.logicalDpiX() * (60 / 25.4), p.logicalDpiY() * (3500 / 25.4))) p.setOutputFormat(QPrinter.NativeFormat) doc.setHtml(u'%s' % context) doc.print_(p)
class PrintData: """Class to handle printing of tree output data. Stores print data and main printing functions. """ def __init__(self, localControl): """Initialize the print data. Arguments: localControl -- a reference to the parent local control """ self.localControl = localControl self.outputGroup = None self.printWhat = PrintScope.entireTree self.includeRoot = True self.openOnly = False self.printer = QPrinter(QPrinter.HighResolution) self.pageLayout = self.printer.pageLayout() self.setDefaults() self.adjustSpacing() def setDefaults(self): """Set all paparmeters saved in TreeLine files to default values. """ self.drawLines = True self.widowControl = True self.indentFactor = 2.0 self.pageLayout.setUnits(QPageLayout.Inch) self.pageLayout.setPageSize(QPageSize(QPageSize.Letter)) self.pageLayout.setOrientation(QPageLayout.Portrait) self.pageLayout.setMargins(QMarginsF(*(_defaultMargin, ) * 4)) self.headerMargin = _defaultHeaderPos self.footerMargin = _defaultHeaderPos self.numColumns = 1 self.columnSpacing = _defaultColumnSpace self.headerText = '' self.footerText = '' self.useDefaultFont = True self.setDefaultFont() def setDefaultFont(self): """Set the default font initially and based on an output font change. """ self.defaultFont = QTextDocument().defaultFont() fontName = globalref.miscOptions['OutputFont'] if fontName: self.defaultFont.fromString(fontName) if self.useDefaultFont: self.mainFont = self.defaultFont def adjustSpacing(self): """Adjust line spacing & indent size based on font & indent factor. """ self.lineSpacing = QFontMetrics(self.mainFont, self.printer).lineSpacing() self.indentSize = self.indentFactor * self.lineSpacing def fileData(self): """Return a dictionary of non-default settings for storage. """ data = {} if not self.drawLines: data['printlines'] = False if not self.widowControl: data['printwidowcontrol'] = False if self.indentFactor != 2.0: data['printindentfactor'] = self.indentFactor pageSizeId = self.pageLayout.pageSize().id() if pageSizeId == QPageSize.Custom: paperWidth, paperHeight = self.roundedPaperSize() data['printpaperwidth'] = paperWidth data['printpaperheight'] = paperHeight elif pageSizeId != QPageSize.Letter: data['printpapersize'] = self.paperSizeName(pageSizeId) if self.pageLayout.orientation() != QPageLayout.Portrait: data['printportrait'] = False if self.roundedMargins() != (_defaultMargin, ) * 4: data['printmargins'] = list(self.roundedMargins()) if self.headerMargin != _defaultHeaderPos: data['printheadermargin'] = self.headerMargin if self.footerMargin != _defaultHeaderPos: data['printfootermargin'] = self.footerMargin if self.numColumns > 1: data['printnumcolumns'] = self.numColumns if self.columnSpacing != _defaultColumnSpace: data['printcolumnspace'] = self.columnSpacing if self.headerText: data['printheadertext'] = self.headerText if self.footerText: data['printfootertext'] = self.footerText if not self.useDefaultFont: data['printfont'] = self.mainFont.toString() return data def readData(self, data): """Restore saved settings from a dictionary. Arguments: data -- a dictionary of stored non-default settings """ self.setDefaults() # necessary for undo/redo self.drawLines = data.get('printlines', True) self.widowControl = data.get('printwidowcontrol', True) self.indentFactor = data.get('printindentfactor', 2.0) if 'printpapersize' in data: self.pageLayout.setPageSize( QPageSize(getattr(QPageSize, data['printpapersize']))) self.pageLayout.setMargins(QMarginsF(*(_defaultMargin, ) * 4)) if 'printpaperwidth' in data and 'printpaperheight' in data: width = data['printpaperwidth'] height = data['printpaperheight'] self.pageLayout.setPageSize( QPageSize(QSizeF(width, height), QPageSize.Inch)) self.pageLayout.setMargins(QMarginsF(*(_defaultMargin, ) * 4)) if not data.get('printportrait', True): self.pageLayout.setOrientation(QPageLayout.Landscape) if 'printmargins' in data: margins = data['printmargins'] self.pageLayout.setMargins(QMarginsF(*margins)) self.headerMargin = data.get('printheadermargin', _defaultHeaderPos) self.footerMargin = data.get('printfootermargin', _defaultHeaderPos) self.numColumns = data.get('printnumcolumns', 1) self.columnSpacing = data.get('printcolumnspace', _defaultColumnSpace) self.headerText = data.get('printheadertext', '') self.footerText = data.get('printfootertext', '') if 'printfont' in data: self.useDefaultFont = False self.mainFont.fromString(data['printfont']) self.adjustSpacing() def roundedMargins(self): """Return a tuple of rounded page margins in inches. Rounds to nearest .01" to avoid Qt unit conversion artifacts. """ margins = self.pageLayout.margins(QPageLayout.Inch) return tuple( round(margin, 2) for margin in (margins.left(), margins.top(), margins.right(), margins.bottom())) def roundedPaperSize(self): """Return a tuple of rounded paper width and height. Rounds to nearest .01" to avoid Qt unit conversion artifacts. """ size = self.pageLayout.fullRect(QPageLayout.Inch) return (round(size.width(), 2), round(size.height(), 2)) def paperSizeName(self, sizeId=None): """Return a QPageSize attribute name matching the paper size ID. Arguments: sizeId -- the Qt size ID, if None, use current size """ if sizeId == None: sizeId = self.pageLayout.pageSize().id() matches = [] for name, num in vars(QPageSize).items(): if num == sizeId: matches.append(name) if not matches: return 'Custom' if len(matches) > 1: text = QPageSize(sizeId).name().split(None, 1)[0] for name in matches: if name == text: return name return matches[0] def setupData(self): """Load data to be printed and set page info. """ if self.printWhat == PrintScope.entireTree: selSpots = self.localControl.structure.rootSpots() else: selSpots = ( self.localControl.currentSelectionModel().selectedSpots()) if not selSpots: selSpots = self.localControl.structure.rootSpots() self.outputGroup = treeoutput.OutputGroup( selSpots, self.includeRoot, self.printWhat != PrintScope.selectNode, self.openOnly) self.paginate() def paginate(self): """Define the pages and locations of output items and set page range. """ pageNum = 1 columnNum = 0 pagePos = 0 itemSplit = False self.checkPageLayout() heightAvail = (self.pageLayout.paintRect().height() * self.printer.logicalDpiY()) columnSpacing = int(self.columnSpacing * self.printer.logicalDpiX()) widthAvail = ( (self.pageLayout.paintRect().width() * self.printer.logicalDpiX() - columnSpacing * (self.numColumns - 1)) // self.numColumns) newGroup = treeoutput.OutputGroup([]) while self.outputGroup: item = self.outputGroup.pop(0) widthRemain = widthAvail - item.level * self.indentSize if pagePos != 0 and (newGroup[-1].addSpace or item.addSpace): pagePos += self.lineSpacing if item.siblingPrefix: siblings = treeoutput.OutputGroup([]) siblings.append(item) while True: item = siblings.combineLines() item.setDocHeight(self.printer, widthRemain, self.mainFont, True) if pagePos + item.height > heightAvail: self.outputGroup.insert(0, siblings.pop()) item = (siblings.combineLines() if siblings else None) break if (self.outputGroup and item.level == self.outputGroup[0].level and item.equalPrefix(self.outputGroup[0])): siblings.append(self.outputGroup.pop(0)) else: break if item: item.setDocHeight(self.printer, widthRemain, self.mainFont, True) if item.height > heightAvail and not itemSplit: item, newItem = item.splitDocHeight( heightAvail - pagePos, heightAvail, self.printer, widthRemain, self.mainFont) if newItem: self.outputGroup.insert(0, newItem) itemSplit = True if item and (pagePos + item.height <= heightAvail or pagePos == 0): item.pageNum = pageNum item.columnNum = columnNum item.pagePos = pagePos newGroup.append(item) pagePos += item.height else: if columnNum + 1 < self.numColumns: columnNum += 1 else: pageNum += 1 columnNum = 0 pagePos = 0 itemSplit = False if item: self.outputGroup.insert(0, item) if self.widowControl and not item.siblingPrefix: moveItems = [] moveHeight = 0 level = item.level while (newGroup and not newGroup[-1].siblingPrefix and newGroup[-1].level == level - 1 and ((newGroup[-1].pageNum == pageNum - 1 and newGroup[-1].columnNum == columnNum) or (newGroup[-1].pageNum == pageNum and newGroup[-1].columnNum == columnNum - 1))): moveItems.insert(0, newGroup.pop()) moveHeight += moveItems[0].height level -= 1 if (moveItems and newGroup and moveHeight < (heightAvail // 5)): self.outputGroup[0:0] = moveItems else: newGroup.extend(moveItems) self.outputGroup = newGroup self.outputGroup.loadFamilyRefs() self.printer.setFromTo(1, pageNum) def checkPageLayout(self): """Check and set the page layout on the current printer. Verify that the layout settings match the printer, adjust if required. """ if not self.printer.setPageLayout(self.pageLayout): tempPrinter = QPrinter() tempPageLayout = tempPrinter.pageLayout() tempPageLayout.setUnits(QPageLayout.Inch) pageSizeIssue = False defaultPageSize = tempPageLayout.pageSize() tempPageLayout.setPageSize(self.pageLayout.pageSize()) if not tempPrinter.setPageLayout(tempPageLayout): pageSizeIssue = True tempPageLayout.setPageSize(defaultPageSize) marginIssue = not (tempPageLayout.setMargins( self.pageLayout.margins()) and tempPrinter.setPageLayout(tempPageLayout)) if marginIssue: margin = 0.1 while True: if (tempPageLayout.setMargins(QMarginsF(*(margin, ) * 4)) and tempPrinter.setPageLayout(tempPageLayout)): break margin += 0.1 newMargins = [] for oldMargin in self.roundedMargins(): newMargins.append( oldMargin if oldMargin >= margin else margin) tempPageLayout.setMargins(QMarginsF(*newMargins)) tempPageLayout.setOrientation(self.pageLayout.orientation()) self.printer.setPageLayout(tempPageLayout) if not pageSizeIssue and not marginIssue: return if pageSizeIssue and marginIssue: msg = _('Warning: Page size and margin settings unsupported ' 'on current printer.\nSave page adjustments?') elif pageSizeIssue: msg = _('Warning: Page size setting unsupported ' 'on current printer.\nSave adjustment?') else: msg = _('Warning: Margin settings unsupported ' 'on current printer.\nSave adjustments?') ans = QMessageBox.warning(QApplication.activeWindow(), 'TreeLine', msg, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if ans == QMessageBox.Yes: self.pageLayout = tempPageLayout def paintData(self, printer): """Paint data to be printed to the printer. """ pageNum = 1 try: maxPageNum = self.outputGroup[-1].pageNum except IndexError: # printing empty branch maxPageNum = 1 if self.printer.printRange() != QPrinter.AllPages: pageNum = self.printer.fromPage() maxPageNum = self.printer.toPage() painter = QPainter() if not painter.begin(self.printer): QMessageBox.warning(QApplication.activeWindow(), 'TreeLine', _('Error initializing printer')) QApplication.setOverrideCursor(Qt.WaitCursor) while True: self.paintPage(pageNum, painter) if pageNum == maxPageNum: QApplication.restoreOverrideCursor() return pageNum += 1 self.printer.newPage() def paintPage(self, pageNum, painter): """Paint data for the given page to the printer. Arguments: pageNum -- the page number to be printed painter -- the painter for this print job """ paintContext = QAbstractTextDocumentLayout.PaintContext() # set context text color to black to wrok with dark app themes paintContext.palette = QPalette() paintContext.palette.setColor(QPalette.Text, Qt.black) try: totalNumPages = self.outputGroup[-1].pageNum except IndexError: # printing empty branch totalNumPages = 1 headerDoc = self.headerFooterDoc(True, pageNum, totalNumPages) if headerDoc: layout = headerDoc.documentLayout() layout.setPaintDevice(self.printer) headerDoc.setTextWidth(self.pageLayout.paintRect().width() * self.printer.logicalDpiX()) painter.save() topMargin = self.pageLayout.margins(QPageLayout.Inch).top() headerDelta = ((self.headerMargin - topMargin) * self.printer.logicalDpiX()) painter.translate(0, int(headerDelta)) layout.draw(painter, paintContext) painter.restore() painter.save() columnSpacing = int(self.columnSpacing * self.printer.logicalDpiX()) columnDelta = ( (self.pageLayout.paintRect().width() * self.printer.logicalDpiX() - columnSpacing * (self.numColumns - 1)) / self.numColumns) + columnSpacing for columnNum in range(self.numColumns): if columnNum > 0: painter.translate(columnDelta, 0) self.paintColumn(pageNum, columnNum, painter, paintContext) painter.restore() footerDoc = self.headerFooterDoc(False, pageNum, totalNumPages) if footerDoc: layout = footerDoc.documentLayout() layout.setPaintDevice(self.printer) footerDoc.setTextWidth(self.pageLayout.paintRect().width() * self.printer.logicalDpiX()) painter.save() bottomMargin = self.pageLayout.margins(QPageLayout.Inch).bottom() footerDelta = ((bottomMargin - self.footerMargin) * self.printer.logicalDpiX()) painter.translate( 0, self.pageLayout.paintRect().height() * self.printer.logicalDpiX() + int(footerDelta) - self.lineSpacing) layout.draw(painter, paintContext) painter.restore() def paintColumn(self, pageNum, columnNum, painter, paintContext): """Paint data for the given column to the printer. Arguments: pageNum -- the page number to be printed columnNum -- the column number to be printed painter -- the painter for this print job """ columnItems = [ item for item in self.outputGroup if item.pageNum == pageNum and item.columnNum == columnNum ] for item in columnItems: layout = item.doc.documentLayout() painter.save() painter.translate(item.level * self.indentSize, item.pagePos) layout.draw(painter, paintContext) painter.restore() if self.drawLines: self.addPrintLines(pageNum, columnNum, columnItems, painter) def addPrintLines(self, pageNum, columnNum, columnItems, painter): """Paint lines between parent and child items on the page. Arguments: pageNum -- the page number to be printed columnNum -- the column number to be printed columnItems -- a list of items in this column painter -- the painter for this print job """ parentsDrawn = set() horizOffset = self.indentSize // 2 vertOffset = self.lineSpacing // 2 heightAvail = (self.pageLayout.paintRect().height() * self.printer.logicalDpiY()) for item in columnItems: if item.level > 0: indent = item.level * self.indentSize vertPos = item.pagePos + vertOffset painter.drawLine(indent - horizOffset, vertPos, indent - self.lineSpacing // 4, vertPos) parent = item.parentItem while parent: if parent in parentsDrawn: break lineStart = 0 lineEnd = heightAvail if (parent.pageNum == pageNum and parent.columnNum == columnNum): lineStart = parent.pagePos + parent.height if (parent.lastChildItem.pageNum == pageNum and parent.lastChildItem.columnNum == columnNum): lineEnd = parent.lastChildItem.pagePos + vertOffset if (parent.lastChildItem.pageNum > pageNum or (parent.lastChildItem.pageNum == pageNum and parent.lastChildItem.columnNum >= columnNum)): horizPos = ((parent.level + 1) * self.indentSize - horizOffset) painter.drawLine(horizPos, lineStart, horizPos, lineEnd) parentsDrawn.add(parent) parent = parent.parentItem def formatHeaderFooter(self, header=True, pageNum=1, numPages=1): """Return an HTML table formatted header or footer. Return an empty string if no header/footer is defined. Arguments: header -- return header if True, footer if false """ if header: textParts = printdialogs.splitHeaderFooter(self.headerText) else: textParts = printdialogs.splitHeaderFooter(self.footerText) if not textParts: return '' fileInfoFormat = self.localControl.structure.treeFormats.fileInfoFormat fileInfoNode = self.localControl.structure.fileInfoNode fileInfoFormat.updateFileInfo(self.localControl.filePathObj, fileInfoNode) fileInfoNode.data[fileInfoFormat.pageNumFieldName] = repr(pageNum) fileInfoNode.data[fileInfoFormat.numPagesFieldName] = repr(numPages) fileInfoFormat.changeOutputLines(textParts, keepBlanks=True) textParts = fileInfoFormat.formatOutput(fileInfoNode, keepBlanks=True) alignments = ('left', 'center', 'right') result = ['<table width="100%"><tr>'] for text, align in zip(textParts, alignments): if text: result.append('<td align="{0}">{1}</td>'.format(align, text)) if len(result) > 1: result.append('</tr></table>') return '\n'.join(result) return '' def headerFooterDoc(self, header=True, pageNum=1, numPages=1): """Return a text document for the header or footer. Return None if no header/footer is defined. Arguments: header -- return header if True, footer if false """ text = self.formatHeaderFooter(header, pageNum, numPages) if text: doc = QTextDocument() doc.setHtml(text) doc.setDefaultFont(self.mainFont) frameFormat = doc.rootFrame().frameFormat() frameFormat.setBorder(0) frameFormat.setMargin(0) frameFormat.setPadding(0) doc.rootFrame().setFrameFormat(frameFormat) return doc return None def printSetup(self): """Show a dialog to set margins, page size and other printing options. """ setupDialog = printdialogs.PrintSetupDialog( self, True, QApplication.activeWindow()) setupDialog.exec_() def printPreview(self): """Show a preview of printing results. """ self.setupData() previewDialog = printdialogs.PrintPreviewDialog( self, QApplication.activeWindow()) previewDialog.previewWidget.paintRequested.connect(self.paintData) if globalref.genOptions['SaveWindowGeom']: previewDialog.restoreDialogGeom() previewDialog.exec_() def filePrint(self): """Show dialog and print tree output based on current options. """ self.printer.setOutputFormat(QPrinter.NativeFormat) self.setupData() printDialog = QPrintDialog(self.printer, QApplication.activeWindow()) if printDialog.exec_() == QDialog.Accepted: self.paintData(self.printer) def filePrintPdf(self): """Export to a PDF file with current options. """ filters = ';;'.join( (globalref.fileFilters['pdf'], globalref.fileFilters['all'])) defaultFilePath = str(globalref.mainControl.defaultPathObj()) defaultFilePath = os.path.splitext(defaultFilePath)[0] if os.path.basename(defaultFilePath): defaultFilePath = '{0}.{1}'.format(defaultFilePath, 'pdf') filePath, selectFilter = QFileDialog.getSaveFileName( QApplication.activeWindow(), _('TreeLine - Export PDF'), defaultFilePath, filters) if not filePath: return if not os.path.splitext(filePath)[1]: filePath = '{0}.{1}'.format(filePath, 'pdf') origFormat = self.printer.outputFormat() self.printer.setOutputFormat(QPrinter.PdfFormat) self.printer.setOutputFileName(filePath) self.adjustSpacing() self.setupData() self.paintData(self.printer) self.printer.setOutputFormat(origFormat) self.printer.setOutputFileName('') self.adjustSpacing()
def print_labels_to_printer(self, printer: QtPrintSupport.QPrinter): dpi_x = printer.logicalDpiX() dpi_y = printer.logicalDpiY() painter = QtGui.QPainter() painter.begin(printer) shortcuts = sorted( self.get_shortcuts(), key=lambda shortcut_item: "{}-{}".format( QtGui.QColor(shortcut_item.label.background_color).rgb() if shortcut_item.label.background_color else 0, shortcut_item. name)) x = 0 y = 0 max_end_y = 0 shortcut: Shortcut for shortcut in shortcuts: icon_path = shortcut.label.icon_path if not icon_path: continue label_width = LengthUnit.length_to_pixel( Config.labels_length_unit, shortcut.label.width or Config.default_label_width, dpi_x) label_height = LengthUnit.length_to_pixel( Config.labels_length_unit, shortcut.label.height or Config.default_label_height, dpi_y) icon_margin_x = LengthUnit.length_to_pixel( Config.labels_length_unit, Config.label_icon_margin, dpi_x) icon_margin_y = LengthUnit.length_to_pixel( Config.labels_length_unit, Config.label_icon_margin, dpi_y) end_x = x + label_width end_y = y + label_height max_end_y = max(max_end_y, end_y) if end_x > printer.width(): x = 0 y = max_end_y end_x = x + label_width end_y = y + label_height if end_y > printer.height(): printer.newPage() x = 0 y = 0 end_x = x + label_width end_y = y + label_height max_end_y = end_y icon = QtGui.QImage(icon_path) scaled_icon: QtGui.QImage = icon.scaled( label_width - icon_margin_x, label_height - icon_margin_y, QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation) if shortcut.label.background_color: painter.fillRect(x, y, label_width, label_height, QtGui.QColor(shortcut.label.background_color)) icon_width = scaled_icon.width() icon_height = scaled_icon.height() painter.drawImage(x + (label_width - icon_width) / 2, y + (label_height - icon_height) / 2, scaled_icon) painter.setPen(QtGui.QColor("black")) painter.drawRect(x, y, label_width, label_height) x = end_x
class Form(QDialog): def __init__(self, parent=None): super(Form, self).__init__(parent) self.printer = QPrinter() self.printer.setPageSize(QPrinter.Letter) self.generateFakeStatements() self.table = QTableWidget() self.populateTable() cursorButton = QPushButton("Print via Q&Cursor") htmlButton = QPushButton("Print via &HTML") painterButton = QPushButton("Print via Q&Painter") quitButton = QPushButton("&Quit") buttonLayout = QHBoxLayout() buttonLayout.addWidget(cursorButton) buttonLayout.addWidget(htmlButton) buttonLayout.addWidget(painterButton) buttonLayout.addStretch() buttonLayout.addWidget(quitButton) layout = QVBoxLayout() layout.addWidget(self.table) layout.addLayout(buttonLayout) self.setLayout(layout) cursorButton.clicked.connect(self.printViaQCursor) htmlButton.clicked.connect(self.printViaHtml) painterButton.clicked.connect(self.printViaQPainter) quitButton.clicked.connect(self.accept) self.setWindowTitle("Printing") def generateFakeStatements(self): self.statements = [] statement = Statement("Consality", "Ms S. Royal", "234 Rue Saint Hyacinthe, 750201, Paris") statement.transactions.append((QDate(2007, 8, 11), 2342)) statement.transactions.append((QDate(2007, 9, 10), 2342)) statement.transactions.append((QDate(2007, 10, 9), 2352)) statement.transactions.append((QDate(2007, 10, 17), -1500)) statement.transactions.append((QDate(2007, 11, 12), 2352)) statement.transactions.append((QDate(2007, 12, 10), 2352)) statement.transactions.append((QDate(2007, 12, 20), -7500)) statement.transactions.append((QDate(2007, 12, 20), 250)) statement.transactions.append((QDate(2008, 1, 10), 2362)) self.statements.append(statement) statement = Statement( "Demamitur Plc", "Mr G. Brown", "14 Tall Towers, Tower Hamlets, London, WC1 3BX") statement.transactions.append((QDate(2007, 5, 21), 871)) statement.transactions.append((QDate(2007, 6, 20), 542)) statement.transactions.append((QDate(2007, 7, 20), 1123)) statement.transactions.append((QDate(2007, 7, 20), -1928)) statement.transactions.append((QDate(2007, 8, 13), -214)) statement.transactions.append((QDate(2007, 9, 15), -3924)) statement.transactions.append((QDate(2007, 9, 15), 2712)) statement.transactions.append((QDate(2007, 9, 15), -273)) #statement.transactions.append((QDate(2007, 11, 8), -728)) #statement.transactions.append((QDate(2008, 2, 7), 228)) #statement.transactions.append((QDate(2008, 3, 13), -508)) #statement.transactions.append((QDate(2008, 3, 22), -2481)) #statement.transactions.append((QDate(2008, 4, 5), 195)) self.statements.append(statement) def populateTable(self): headers = ["Company", "Contact", "Address", "Balance"] self.table.setColumnCount(len(headers)) self.table.setHorizontalHeaderLabels(headers) self.table.setRowCount(len(self.statements)) for row, statement in enumerate(self.statements): self.table.setItem(row, 0, QTableWidgetItem(statement.company)) self.table.setItem(row, 1, QTableWidgetItem(statement.contact)) self.table.setItem(row, 2, QTableWidgetItem(statement.address)) item = QTableWidgetItem("$ {0:,.2f}".format( float(statement.balance()))) item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter) self.table.setItem(row, 3, item) self.table.resizeColumnsToContents() def printViaHtml(self): htmltext = "" # for statement in self.statements: # date = QDate.currentDate().toString(DATE_FORMAT) # address = html.escape(statement.address).replace( # ",", "<br>") # contact = html.escape(statement.contact) # balance = statement.balance() # htmltext += ("<p align=right><img src=':/logo.png'></p>" # "<p align=right>Greasy Hands Ltd." # "<br>New Lombard Street" # "<br>London<br>WC13 4PX<br>{0}</p>" # "<p>{1}</p><p>Dear {2},</p>" # "<p>The balance of your account is $ {3:,.2f}.").format( # date, address, contact, float(balance)) # if balance < 0: # htmltext += (" <p><font color=red><b>Please remit the " # "amount owing immediately.</b></font>") # else: # htmltext += (" We are delighted to have done business " # "with you.") # htmltext += ("</p><p> </p><p>" # "<table border=1 cellpadding=2 " # "cellspacing=2><tr><td colspan=3 align=center>" # "Transactions1</td></tr>") # for date, amount in statement.transactions: # color, status = "black", "Credit" # if amount < 0: # color, status = "red", "Debit" # htmltext += ("<tr><td align=right width=200>{0}</td>" # "<td>{1}</td><td align=right>" # "<font color={2}>$ {3:,.2f}</font></td></tr>".format( # date.toString(DATE_FORMAT), status, color,float(abs(amount)))) # htmltext += ("</table></p><p style='page-break-after:always;'>" # "We hope to continue doing " # "business with you,<br>Yours sincerely," # "<br><br>K. Longrey, Manager</p>") htmltext = "<p>美莱项目组欢迎您!</p>" dialog = QPrintDialog(self.printer, self) if dialog.exec_(): #printer # print(self.printer.logicalDpiX()) # print(self.printer.logicalDpiX() * (257 / 25.4)) # print(self.printer.logicalDpiY()) # print(self.printer.logicalDpiY() * (125 / 25.4)) qsizeF = QSizeF(self.printer.logicalDpiX() * (257 / 25.4), self.printer.logicalDpiY() * (125 / 25.4)) # qsizeF = QSizeF(self.printer.logicalDpiX() * (210 / 25.4), self.printer.logicalDpiY() * (297 / 25.4)); self.printer.setPageSize(QPrinter.Custom) self.printer.setPaperName("小票2") paperSize = QSizeF(257, 125) self.printer.setPaperSize(paperSize, QPrinter.Millimeter) # self.printer.setPageSizeMM(qsizeF) # self.printer.setFullPage(True); # self.printer.setOrientation(QPrinter.Portrait); # self.printer.setOutputFormat(QPrinter.NativeFormat) # document document = QTextDocument() document.setPageSize(qsizeF) font = QFont() font.setPointSize(6) document.setDefaultFont(font) document.setHtml(htmltext) document.print_(self.printer) def printViaQCursor(self): dialog = QPrintDialog(self.printer, self) if not dialog.exec_(): return logo = QPixmap(":/logo.png") headFormat = QTextBlockFormat() headFormat.setAlignment(Qt.AlignLeft) headFormat.setTextIndent(self.printer.pageRect().width() - logo.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 for statement in self.statements: cursor.insertBlock(headFormat, headCharFormat) cursor.insertImage(":/logo.png") for text in ("Greasy Hands Ltd.", "New Lombard Street", "London", "WC13 4PX", QDate.currentDate().toString(DATE_FORMAT)): cursor.insertBlock(headFormat, headCharFormat) cursor.insertText(text) for line in statement.address.split(", "): cursor.insertBlock(bodyFormat, bodyCharFormat) cursor.insertText(line) cursor.insertBlock(bodyFormat) cursor.insertBlock(bodyFormat, bodyCharFormat) cursor.insertText("Dear {0},".format(statement.contact)) cursor.insertBlock(bodyFormat) cursor.insertBlock(bodyFormat, bodyCharFormat) balance = statement.balance() cursor.insertText( "The balance of your account is $ {0:,.2f}.".format( float(balance))) if balance < 0: cursor.insertBlock(bodyFormat, redBodyCharFormat) cursor.insertText("Please remit the amount owing " "immediately.") else: cursor.insertBlock(bodyFormat, bodyCharFormat) cursor.insertText("We are delighted to have done " "business with you.") cursor.insertBlock(bodyFormat, bodyCharFormat) cursor.insertText("Transactions:") table = cursor.insertTable(len(statement.transactions), 3, tableFormat) row = 0 for date, amount in statement.transactions: cellCursor = table.cellAt(row, 0).firstCursorPosition() cellCursor.setBlockFormat(rightBodyFormat) cellCursor.insertText(date.toString(DATE_FORMAT), bodyCharFormat) cellCursor = table.cellAt(row, 1).firstCursorPosition() if amount > 0: cellCursor.insertText("Credit", bodyCharFormat) else: cellCursor.insertText("Debit", bodyCharFormat) cellCursor = table.cellAt(row, 2).firstCursorPosition() cellCursor.setBlockFormat(rightBodyFormat) format = bodyCharFormat if amount < 0: format = redBodyCharFormat cellCursor.insertText("$ {0:,.2f}".format(float(amount)), format) row += 1 cursor.setPosition(mainFrame.lastPosition()) cursor.insertBlock(bodyFormat, bodyCharFormat) cursor.insertText("董道王测试,高伟达,杭州美莱 " "丰胸,") cursor.insertBlock(bodyFormat, bodyCharFormat) cursor.insertText("结果保存在操作者自己的电脑上") cursor.insertBlock(bodyFormat) if page == len(self.statements): cursor.insertBlock(bodyFormat, bodyCharFormat) else: cursor.insertBlock(lastParaBodyFormat, bodyCharFormat) cursor.insertText("K. Longrey, Manager") page += 1 document.print_(self.printer) def printViaQPainter(self): dialog = QPrintDialog(self.printer, self) if not dialog.exec_(): return LeftMargin = 72 sansFont = QFont("宋体", 9) sansLineHeight = QFontMetrics(sansFont).height() serifFont = QFont("宋体", 9) fm = QFontMetrics(serifFont) DateWidth = fm.width(" September 99, 2999 ") CreditWidth = fm.width(" Credit ") AmountWidth = fm.width(" W999999.99 ") serifLineHeight = fm.height() logo = QPixmap(":/logo.png") painter = QPainter(self.printer) pageRect = self.printer.pageRect() page = 1 for statement in self.statements: painter.save() y = 0 x = pageRect.width() - logo.width() - LeftMargin painter.drawPixmap(x, 0, logo) y += logo.height() + sansLineHeight painter.setFont(sansFont) painter.drawText(x, y, "Greasy Hands Ltd.") y += sansLineHeight painter.drawText(x, y, "New Lombard Street") y += sansLineHeight painter.drawText(x, y, "London") y += sansLineHeight painter.drawText(x, y, "WC13 4PX") y += sansLineHeight painter.drawText(x, y, QDate.currentDate().toString(DATE_FORMAT)) y += sansLineHeight painter.setFont(serifFont) x = LeftMargin for line in statement.address.split(", "): painter.drawText(x, y, line) y += serifLineHeight y += serifLineHeight painter.drawText(x, y, "Dear {0},".format(statement.contact)) y += serifLineHeight balance = statement.balance() painter.drawText( x, y, "董道王测试,高伟达,杭州美莱 $ {0:,.2f}".format(float(balance))) y += serifLineHeight if balance < 0: painter.setPen(Qt.red) text = "请立即还款." else: text = ("我们主要用于商业化 " "和你.") painter.drawText(x, y, text) painter.setPen(Qt.black) y += int(serifLineHeight * 1.5) painter.drawText(x, y, "谢谢:") y += serifLineHeight option = QTextOption(Qt.AlignRight | Qt.AlignVCenter) for date, amount in statement.transactions: x = LeftMargin h = int(fm.height() * 1.3) painter.drawRect(x, y, DateWidth, h) painter.drawText(QRectF(x + 3, y + 3, DateWidth - 6, h - 6), date.toString(DATE_FORMAT), option) x += DateWidth painter.drawRect(x, y, CreditWidth, h) text = "Credit" if amount < 0: text = "Debit" painter.drawText(QRectF(x + 3, y + 3, CreditWidth - 6, h - 6), text, option) x += CreditWidth painter.drawRect(x, y, AmountWidth, h) if amount < 0: painter.setPen(Qt.red) painter.drawText(QRectF(x + 3, y + 3, AmountWidth - 6, h - 6), "$ {0:,.2f}".format(float(amount)), option) painter.setPen(Qt.black) y += h y += serifLineHeight x = LeftMargin painter.drawText(x, y, "We hope to continue doing " "business with you,") y += serifLineHeight painter.drawText(x, y, "Yours sincerely") y += serifLineHeight * 3 painter.drawText(x, y, "K. Longrey, Manager") x = LeftMargin y = pageRect.height() - 72 painter.drawLine(x, y, pageRect.width() - LeftMargin, y) y += 2 font = QFont("宋体", 9) font.setItalic(True) painter.setFont(font) option = QTextOption(Qt.AlignCenter) option.setWrapMode(QTextOption.WordWrap) painter.drawText( QRectF(x, y, pageRect.width() - 2 * LeftMargin, 31), "The contents of this letter are for information " "only and do not form part of any contract.", option) page += 1 if page <= len(self.statements): self.printer.newPage() painter.restore()