如何使用 PyQt5 将 QTableWidget 数据转换为 PDF Python

How to convert QTableWidget data to PDF using PyQt5 Python

我正在做一个 python 项目,我的数据存储在 QTableWidget 中。我必须将此数据导出到 excel sheetPDF。我已经能够使用以下代码将数据导出到 excel sheet。但无法理解如何将其转换为 PDF.

filename, _ = QFileDialog.getSaveFileName(self, 'Save File', '', ".xls(*.xls)")
wbk = xlwt.Workbook()
sheet = wbk.add_sheet("sheet", cell_overwrite_ok=True)
style = xlwt.XFStyle()
font = xlwt.Font()
font.bold = True
style.font = font
model = self.home_ui.reports_table.model()

for c in range(model.columnCount()):
    text = model.headerData(c, QtCore.Qt.Horizontal)
    first_col = sheet.col(c+1)
    l = len(text)
    first_col.width = (256 * l) + 1000
    sheet.write(0, c + 1, text, style=style)

for r in range(model.rowCount()):
    text = model.headerData(r, QtCore.Qt.Vertical)
    sheet.write(r + 1, 0, text, style=style)

for c in range(model.columnCount()):
    for r in range(model.rowCount()):
        text = model.data(model.index(r, c))
        sheet.write(r + 1, c + 1, text)

wbk.save(filename)

以上代码运行良好并将数据保存到 excel。

我研究了其他具有相同主题的 questions,但它们都是用 C++ 编写的。我正在寻找 python 等价物。

任何人都可以给我一些关于如何将数据转换为 PDF 的好的建议。请帮忙。谢谢

当您查看答案时,您不仅应该看到代码,还应该看到解决方案本身,即后台的逻辑。在这种特殊情况下,解决方案是创建一个显示 table 内容的 HTML,并使用 QTextDocument 和 QPrinter 将 HTML 打印为 PDF。

综上所述,逻辑清晰,无需翻译,从头实现即可。

from PyQt5 import QtCore, QtGui, QtWidgets, QtPrintSupport

app = QtWidgets.QApplication([])

w = QtWidgets.QTableWidget(10, 10)
for i in range(10):
    for j in range(10):
        it = QtWidgets.QTableWidgetItem("{}-{}".format(i, j))
        w.setItem(i, j, it)


filename = "table.pdf"
model = w.model()

printer = QtPrintSupport.QPrinter(QtPrintSupport.QPrinter.PrinterResolution)
printer.setOutputFormat(QtPrintSupport.QPrinter.PdfFormat)
printer.setPaperSize(QtPrintSupport.QPrinter.A4)
printer.setOrientation(QtPrintSupport.QPrinter.Landscape)
printer.setOutputFileName(filename)

doc = QtGui.QTextDocument()

html = """<html>
<head>
<style>
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}
</style>
</head>"""
html += "<table><thead>"
html += "<tr>"
for c in range(model.columnCount()):
    html += "<th>{}</th>".format(model.headerData(c, QtCore.Qt.Horizontal))

html += "</tr></thead>"
html += "<tbody>"
for r in range(model.rowCount()):
    html += "<tr>"
    for c in range(model.columnCount()):
        html += "<td>{}</td>".format(model.index(r, c).data() or "")
    html += "</tr>"
html += "</tbody></table>"
doc.setHtml(html)
doc.setPageSize(QtCore.QSizeF(printer.pageRect().size()))
doc.print_(printer)