PyQt5-QPrinter控件使用
例如:(原创引用自 http://www.imooc.com/article/73044 )
1 from PyQt5.QtGui import QFont,QTextDocument,QTextCursor 2 from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QSizePolicy, QAction,QDialog 3 from PyQt5.QtPrintSupport import QPrinter, QPrintDialog,QPrintPreviewDialog 4 import sys 5 6 the_text = """ 7 《描写雪的诗句》赏析 8 不知庭霰今朝落,疑是林花昨夜开《苑中遇雪》 9 忽如一夜春风来,千树万树梨花开《白雪歌送武》 10 白雪却嫌春色晚,故穿庭树作飞花《春雪》 11 雪似梅花,梅花似雪。似和不似都奇绝《踏莎行》 12 千峰笋石千株玉,万树松萝万朵银《南秦雪》 13 六出飞花入户时,坐看青竹变琼枝《对雪》 14 地白风色寒,雪花大如手《嘲王历阳不肯饮酒》 15 燕山雪花大如席,片片吹落轩辕台《北风行》 16 白雪纷纷何所似?撒盐空中差可拟《咏雪联句》 17 才见岭头云似盖,已惊岩下雪如尘《南秦雪》 18 """ 19 class MainWindow(QMainWindow): 20 def __init__(self, parent=None): 21 super(MainWindow, self).__init__(parent) 22 self.setWindowTitle("打印功能") 23 24 # 创建文本框 25 self.label = QLabel() 26 self.label.setFont(QFont("Roman times",12,QFont.Bold)) 27 self.label.setText(the_text) 28 self.setCentralWidget(self.label) 29 30 31 # 创建菜单栏 32 self.createMenus() 33 34 35 36 def createMenus(self): 37 # 创建动作一 38 self.printAction1 = QAction(self.tr("打印无预留"), self) 39 self.printAction1.triggered.connect(self.on_printAction1_triggered) 40 41 # 创建动作二 42 self.printAction2 = QAction(self.tr("打印有预留"), self) 43 self.printAction2.triggered.connect(self.on_printAction2_triggered) 44 45 # 创建动作三 46 self.printAction3 = QAction(self.tr("直接打印"), self) 47 self.printAction3.triggered.connect(self.on_printAction3_triggered) 48 49 # 创建动作四 50 self.printAction4 = QAction(self.tr("打印到PDF"), self) 51 self.printAction4.triggered.connect(self.on_printAction4_triggered) 52 53 54 # 创建菜单,添加动作 55 self.printMenu = self.menuBar().addMenu(self.tr("打印")) 56 self.printMenu.addAction(self.printAction1) 57 self.printMenu.addAction(self.printAction2) 58 self.printMenu.addAction(self.printAction3) 59 self.printMenu.addAction(self.printAction4) 60 61 62 63 # 动作一:打印,无预览 64 def on_printAction1_triggered(self): 65 printer = QPrinter() 66 printDialog = QPrintDialog(printer, self) 67 if printDialog.exec_() == QDialog.Accepted: 68 self.handlePaintRequest(printer) 69 70 71 # 动作二:打印,有预览 72 def on_printAction2_triggered(self): 73 dialog = QPrintPreviewDialog() 74 dialog.paintRequested.connect(self.handlePaintRequest) 75 dialog.exec_() 76 77 78 # 动作三:直接打印 79 def on_printAction3_triggered(self): 80 printer = QPrinter() 81 self.handlePaintRequest(printer) 82 83 84 # 动作四:打印到pdf 85 def on_printAction4_triggered(self): 86 printer = QPrinter() 87 printer.setOutputFormat(QPrinter.PdfFormat) 88 printer.setOutputFileName("D:/pdf打印测试.pdf") 89 self.handlePaintRequest(printer) 90 91 92 ## 打印函数 93 def handlePaintRequest(self, printer): 94 document = QTextDocument() 95 cursor = QTextCursor(document) 96 cursor.insertText(self.label.text()) 97 document.print(printer) 98 99 100 if __name__ == "__main__": 101 app = QApplication(sys.argv) 102 main = MainWindow() 103 main.show() 104 sys.exit(app.exec_())