0

How can I convert a Panda DataFrame or QTableWidget to a Pdf?

I have my Sqlite3 database products listed in a QtableWidget (PyQt5) and have them also listed in a panda dataframe. How can I convert one of these to PDF?

I want to generate a product report and any of these methods would suit me. I tried a lot of things I saw on the stack and google but nothing worked.

DataFrame Function

    def gerarRelatorio(self):
        self.banco = sqlite3.connect ( 'Vendas.db' )
        self.cursor = banco.cursor ( )
        engine = create_engine('sqlite:///Vendas.db')
        df = pd.read_sql_table("Produtos", engine)
        print(df)

QtableWidget Function

    def LoadDatabase(self):
        self.banco = sqlite3.connect ( 'Vendas.db' )
        self.cursor = banco.cursor ( )
        query = "SELECT * FROM Produtos"
        result = self.banco.execute ( query )
        self.listaprodutos.setRowCount ( 0 )
        for row_number, row_data in enumerate ( result ):
            self.listaprodutos.insertRow ( row_number )
            for colum_number, data in enumerate ( row_data ):
                self.listaprodutos.setItem(row_number, colum_number, QtWidgets.QTableWidgetItem(str(data)))

1 Answers1

1

you can convert a pandas df to a PDF using the following method:

from PyQt5 import QtGui, QtWidgets
from PyQt5.QtPrintSupport import QPrinter
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QTextDocument
import sys
import pandas as pd

df = pd.DataFrame({'test1':[1],'test2':[2]}) #the dataframe
html = df.to_html()

app = QApplication(sys.argv)
out = QTextDocument()
out.setHtml(html)
printer = QPrinter()
printer.setOutputFileName("test.pdf")
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setPageSize(QPrinter.A4)
printer.setPageMargins(15, 15, 15, 15, QPrinter.Millimeter)
out.print_(printer)

of course you'll have to play around with the pdf formatting to make it look how you want

don't have alot of experience with PyQt5 but you could probably somehow skip the df/html parts if you already have things stored in a QtableWidget

Derek Eden
  • 4,403
  • 3
  • 18
  • 31
  • I tried it but it didn't work. Process finished with exit code -805306369 (0xCFFFFFFF) – Daniel Oliveira Oct 21 '19 at 17:21
  • does the above code example work for you? it works on my machine? what does your df look like... I'm not sure why it wouldn't work if the only variable changing is the df – Derek Eden Oct 21 '19 at 17:38