使用PyQt5 Python将QTableWidget数据转换为PDF,可以通过以下步骤实现:
from PyQt5 import QtWidgets
from PyQt5.QtGui import QTextDocument, QPdfWriter
from PyQt5.QtCore import Qt
app = QtWidgets.QApplication([])
table_widget = QtWidgets.QTableWidget()
table_widget.setRowCount(5) # 设置行数
table_widget.setColumnCount(3) # 设置列数
# 添加数据到表格中
table_widget.setItem(0, 0, QtWidgets.QTableWidgetItem("A"))
table_widget.setItem(0, 1, QtWidgets.QTableWidgetItem("B"))
table_widget.setItem(0, 2, QtWidgets.QTableWidgetItem("C"))
# 添加更多数据...
# 设置表格样式
table_widget.setHorizontalHeaderLabels(["Column 1", "Column 2", "Column 3"])
document = QTextDocument()
cursor = QtGui.QTextCursor(document)
cursor.insertHtml(table_widget.toHtml())
pdf_writer = QPdfWriter("table.pdf")
pdf_writer.setPageSize(QtCore.QSizeF(table_widget.width(), table_widget.height()))
# 将QTextDocument内容写入PDF
document.print_(pdf_writer)
pdf_writer.newPage() # 添加新页面
# 保存PDF文件
pdf_writer.setCreator("Your Name")
pdf_writer.setTitle("Table PDF")
pdf_writer.setSubject("Table to PDF")
pdf_writer.setProducer("PyQt5")
pdf_writer.finish()
完成上述步骤后,运行程序即可将QTableWidget数据转换为PDF文件。
说明:
参考文档:
领取专属 10元无门槛券
手把手带您无忧上云