Skip to content Skip to sidebar Skip to footer

How To Convert Qtablewidget Data To Pdf Using Pyqt5 Python

I am working on a python project where I have data stored in QTableWidget. I have to export this data into excel sheet and PDF. I have been able to export data to excel sheet using

Solution 1:

When you review an answer you should not only see the code but the solution itself, that is, the logic that is in the background. In this particular case the solution is to create an HTML that shows the table content, and use QTextDocument with QPrinter to print the HTML to PDF.

Considering the above, it is not necessary to do the translation since it is enough to implement it from scratch since the logic is clear.

from PyQt5 import QtCore, QtGui, QtWidgets, QtPrintSupport

app = QtWidgets.QApplication([])

w = QtWidgets.QTableWidget(10, 10)
for i inrange(10):
    for j inrange(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 inrange(model.columnCount()):
    html += "<th>{}</th>".format(model.headerData(c, QtCore.Qt.Horizontal))

html += "</tr></thead>"
html += "<tbody>"for r inrange(model.rowCount()):
    html += "<tr>"for c inrange(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)

Post a Comment for "How To Convert Qtablewidget Data To Pdf Using Pyqt5 Python"