python3+PyQt5는 문서 인쇄 기능을 구현합니다.
이 글은 주로 python3+PyQt5의 문서 인쇄 기능을 소개합니다. 관심 있는 친구들은 참고할 수 있습니다.
이 글은 Python3+PyQt5를 사용하여 "python Qt Gui Fast" 프로그래밍을 구현합니다. 책 13장 문서 인쇄 기능. 이 기사에서는 세 가지 방법을 사용합니다.
1. HTML 및 QTextDOcument를 사용하여 문서 인쇄
2. QTextCusor 및 QTextDocument를 사용하여 문서 인쇄
#!/usr/bin/env python3 import math import sys import html from PyQt5.QtPrintSupport import QPrinter,QPrintDialog from PyQt5.QtCore import (QDate, QRectF, Qt) from PyQt5.QtWidgets import (QApplication,QDialog, QHBoxLayout,QPushButton, QTableWidget, QTableWidgetItem,QVBoxLayout) from PyQt5.QtGui import (QFont,QFontMetrics,QPainter,QTextCharFormat, QTextCursor, QTextDocument, QTextFormat, QTextOption, QTextTableFormat, QPixmap,QTextBlockFormat) import qrc_resources from PyQt5.QtPrintSupport import QPrinter,QPrintDialog from PyQt5.QtCore import (QDate, QRectF, Qt) from PyQt5.QtWidgets import (QApplication,QDialog, QHBoxLayout,QPushButton, QTableWidget, QTableWidgetItem,QVBoxLayout) from PyQt5.QtGui import (QFont,QFontMetrics,QPainter,QTextCharFormat, QTextCursor, QTextDocument, QTextFormat, QTextOption, QTextTableFormat, QPixmap,QTextBlockFormat) import qrc_resources DATE_FORMAT = "MMM d, yyyy" class Statement(object): def __init__(self, company, contact, address): self.company = company self.contact = contact self.address = address self.transactions = [] # List of (QDate, float) two-tuples def balance(self): return sum([amount for date, amount in self.transactions]) 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>" "Transactions</td></tr>") for date, amount in statement.transactions: color, status = "black", "Credit" if amount < 0: color, status = "red", "Debit" htmltext += ("<tr><td align=right>{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>") dialog = QPrintDialog(self.printer, self) if dialog.exec_(): document = QTextDocument() 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("We hope to continue doing business " "with you,") cursor.insertBlock(bodyFormat, bodyCharFormat) cursor.insertText("Yours sincerely") 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("Helvetica", 10) sansLineHeight = QFontMetrics(sansFont).height() serifFont = QFont("Times", 11) 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, "The balance of your account is $ {0:,.2f}".format(float(balance))) y += serifLineHeight if balance < 0: painter.setPen(Qt.red) text = "Please remit the amount owing immediately." else: text = ("We are delighted to have done business " "with you.") painter.drawText(x, y, text) painter.setPen(Qt.black) y += int(serifLineHeight * 1.5) painter.drawText(x, y, "Transactions:") 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("Helvetica", 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() if __name__ == "__main__": app = QApplication(sys.argv) form = Form() form.show() app.exec_()
python3+PyQt5는 멀티 스레딩을 지원하는 페이지 인덱서 애플리케이션을 구현합니다
위 내용은 python3+PyQt5는 문서 인쇄 기능을 구현합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











인쇄해야 하는 파일을 열 때 인쇄 미리보기에서 어떤 이유로 인해 테이블 프레임 선이 사라진 것을 발견할 수 있습니다. 이러한 상황이 발생하면 인쇄에도 나타나는 경우 제때에 처리해야 합니다. file 이런 질문이 있으시면 에디터에 가입하여 다음 강좌를 배워보세요. Excel에서 표를 인쇄할 때 테두리 선이 사라지면 어떻게 해야 하나요? 1. 아래 그림과 같이 인쇄할 파일을 엽니다. 2. 아래 그림과 같이 필요한 콘텐츠 영역을 모두 선택합니다. 3. 아래 그림과 같이 마우스 오른쪽 버튼을 클릭하고 "셀 서식" 옵션을 선택합니다. 4. 아래 그림과 같이 창 상단의 "테두리" 옵션을 클릭하세요. 5. 아래 그림과 같이 왼쪽 선 스타일에서 가는 실선 패턴을 선택합니다. 6. '외부 테두리'를 선택하세요.

Doubao 앱에는 많은 AI 생성 기능이 있을 예정인데 Doubao 앱에는 어떤 기능이 있나요? 사용자는 이 소프트웨어를 사용하여 그림을 만들고, AI와 채팅하고, 사용자를 위한 기사를 생성하고, 모든 사람이 노래를 검색하도록 도울 수 있습니다. Doubao 앱의 이 기능 소개는 구체적인 작동 방법을 알려드릴 수 있습니다. 구체적인 내용은 아래와 같으니 한번 살펴보세요! Doubao 앱에는 어떤 기능이 있나요? 답변: 그림 그리기, 채팅, 기사 쓰기, 노래 찾기 등이 가능합니다. 기능 소개: 1. 질문 쿼리: AI를 사용하여 질문에 대한 답변을 더 빠르게 찾을 수 있으며, 모든 종류의 질문을 할 수 있습니다. 2. 이미지 생성: AI를 사용하면 모든 사람에게 일반적인 요구 사항만 알려주면 됩니다. 3. AI 채팅: 사용자와 채팅할 수 있는 AI를 생성할 수 있으며,

vivox100s와 x100 휴대폰은 모두 in vivo 휴대폰 제품군의 대표적인 모델입니다. 두 휴대폰은 각각 서로 다른 시대의 vivo 첨단 기술 수준을 대표하므로 디자인, 성능, 기능 면에서 일정한 차이가 있습니다. 이번 글에서는 소비자들이 자신에게 꼭 맞는 휴대폰을 선택할 수 있도록 두 휴대폰을 성능비교와 기능분석 측면에서 자세히 비교해보겠습니다. 먼저 vivox100s와 x100의 성능 비교를 살펴보겠습니다. vivox100s에는 최신 기술이 탑재되어 있습니다.

인터넷의 급속한 발전으로 셀프미디어라는 개념은 사람들의 마음속에 깊이 뿌리내렸습니다. 그렇다면 셀프미디어란 정확히 무엇인가? 주요 특징과 기능은 무엇입니까? 다음에는 이러한 문제를 하나씩 살펴보겠습니다. 1. 셀프미디어란 정확히 무엇인가? We-media는 이름에서 알 수 있듯이 당신이 미디어라는 뜻입니다. 개인이나 팀이 인터넷 플랫폼을 통해 콘텐츠를 독립적으로 생성, 편집, 출판 및 전파할 수 있는 정보 매체를 말합니다. 신문, 텔레비전, 라디오 등과 같은 전통적인 미디어와 달리 셀프 미디어는 더욱 상호작용적이고 개인화되어 있어 모든 사람이 정보의 생산자이자 전파자가 될 수 있습니다. 2. 셀프미디어의 주요 특징과 기능은 무엇입니까? 1. 낮은 문턱: 셀프미디어의 등장으로 미디어 산업에 진출하기 위한 문턱이 낮아졌습니다. 더 이상 번거로운 장비와 전문팀이 필요하지 않습니다.

Xiaohongshu가 젊은이들 사이에서 인기를 끌면서 점점 더 많은 사람들이 이 플랫폼을 사용하여 자신의 경험과 인생 통찰력의 다양한 측면을 공유하기 시작했습니다. 여러 Xiaohongshu 계정을 효과적으로 관리하는 방법이 중요한 문제가 되었습니다. 이 글에서는 Xiaohongshu 계정 관리 소프트웨어의 일부 기능에 대해 논의하고 Xiaohongshu 계정을 더 잘 관리하는 방법을 살펴보겠습니다. 소셜 미디어가 성장함에 따라 많은 사람들이 여러 소셜 계정을 관리해야 한다는 사실을 깨닫게 되었습니다. 이는 Xiaohongshu 사용자에게도 어려운 과제입니다. 일부 Xiaohongshu 계정 관리 소프트웨어는 자동 콘텐츠 게시, 예약 게시, 데이터 분석 및 기타 기능을 포함하여 사용자가 여러 계정을 보다 쉽게 관리할 수 있도록 도와줍니다. 이러한 도구를 통해 사용자는 자신의 계정을 보다 효율적으로 관리하고 계정 노출과 관심을 높일 수 있습니다. 또한 Xiaohongshu 계정 관리 소프트웨어에는

PHP 팁: 이전 페이지로 돌아가는 기능을 빠르게 구현하세요. 웹 개발을 하다 보면 이전 페이지로 돌아가는 기능을 구현해야 하는 경우가 종종 있습니다. 이러한 작업은 사용자 경험을 향상시키고 사용자가 웹 페이지 간을 더 쉽게 탐색할 수 있게 해줍니다. PHP에서는 몇 가지 간단한 코드를 통해 이 기능을 구현할 수 있습니다. 이번 글에서는 이전 페이지로 돌아가는 기능을 빠르게 구현하는 방법을 소개하고 구체적인 PHP 코드 예제를 제공하겠습니다. PHP에서는 $_SERVER['HTTP_REFERER']를 사용하여 이전 페이지의 URL을 가져올 수 있습니다.

"Discovering Discuz: 정의, 기능 및 코드 예제" 인터넷의 급속한 발전과 함께 커뮤니티 포럼은 사람들이 정보를 얻고 의견을 교환하는 중요한 플랫폼이 되었습니다. 많은 커뮤니티 포럼 시스템 중에서 중국의 잘 알려진 오픈 소스 포럼 소프트웨어인 Discuz는 대다수의 웹 사이트 개발자 및 관리자가 선호합니다. 그렇다면 Discuz는 무엇입니까? 어떤 기능이 있으며 웹사이트에 어떻게 도움이 됩니까? 이 기사에서는 Discuz를 자세히 소개하고 독자가 이에 대해 더 자세히 알아볼 수 있도록 구체적인 코드 예제를 첨부합니다.

가끔 PPT를 사용하다 보면 출력해서 사용해야 하는 경우가 많습니다. 하지만 PPT가 페이지 수가 많다는 것은 모두가 알고 있는 사실입니다. 한 장씩 인쇄하면 정말 낭비일까요? 그래서 제가 직접 테스트해본 결과 PPT 6페이지를 한 페이지에 넣은 후 양면으로 인쇄해도 괜찮습니다. 종이 낭비가 없으며 레이아웃 내용을 명확하게 볼 수 있습니다. 그럼 양면 PPT 시트 6장을 한 페이지에 인쇄하는 방법을 아시나요? 다음으로 설정 방법을 알려드릴 테니 관심 있으신 분들은 꼭 보세요! 단계 세부사항: 1. 먼저 컴퓨터에서 인쇄해야 하는 PPT를 찾은 다음 두 번 클릭하여 엽니다. 페이지 왼쪽 상단에 있는 버튼 옆에 있는 역삼각형을 클릭하고, 드롭다운 메뉴에서 [파일] 버튼을 찾아 클릭한 후 나타나는 정보에서 [인쇄]를 클릭하세요. 2. 클릭
