How to add a printing functionality?

I’m planning on adding a printing function for my desktop app to print out graphs into a paper. However, this is my first time coding in something like this and I’m struggling to find any other source of information that could help me intergrate it.

This is how I have the printing button added:

        self.actionemrpimir = QtWidgets.QAction(MainWindow)
        icon2 = QtGui.QIcon()
        icon2.addPixmap(QtGui.QPixmap("App/image/printer.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.actionemrpimir.setIcon(icon2)
        self.actionemrpimir.setObjectName("actionemrpimir")

What should I do next? Are there any sample codes out there that i could use to test things out? I’m also planning to add internet connection so that I could print the graphs to a nearby printer.

What “graphs” are you referring to, and how are they created?

This is how I’m creating the graphs:

def create_percentage_chart(self):
        if not self.fileName:
            return
        yearList = {}
        level = {}
        rowCount = 0
        with open(self.fileName) as csvfile:
            csvreader = csv.reader(csvfile, delimiter=',')
            for row in csvreader:
                if rowCount == 0:
                    rowCount += 1
                    continue
                if row[0] == "MinTemp":
                    break  # Stop parsing at the weather data section
                if not row[1] in yearList:
                    # Create Dict
                    yearList[row[1]] = []
                    # Append data to dict
                    yearList[row[1]].append({"name": row[0], "level": row[2]})
                else:
                    yearList[row[1]].append({"name": row[0], "level": row[2]})
                rowCount += 1

        series = QtChart.QPercentBarSeries()

        nameList = []
        for x in yearList:
            for z in yearList[x]:
                if not z["name"] in nameList:
                    nameList.append(z["name"])
                if not z["name"] in level:
                    level[z["name"]] = []
                    level[z["name"]].append(float(z["level"]))
                else:
                    level[z["name"]].append(float(z["level"]))
        for x in nameList:
            setattr(self, "set" + str(x), QtChart.QBarSet(str(x)))
            series.append(getattr(self, "set" + str(x)))
            getattr(self, "set" + str(x)).append(level[x])

        chart = QtChart.QChart()
        chart.addSeries(series)
        chart.setTitle("Sample Graph")
        chart.setAnimationOptions(QtChart.QChart.AnimationOption.SeriesAnimations)

        categories = list(yearList.keys())
        axis = QtChart.QBarCategoryAxis()
        axis.append(categories)
        chart.createDefaultAxes()
        chart.setAxisX(axis, series)
        chart.legend().setVisible(True)
        chart.legend().setAlignment(Qt.AlignmentFlag.AlignBottom)

        self.ui.chart_view = QtChart.QChartView(chart)
        self.ui.chart_view.setRenderHint(QPainter.RenderHint.Antialiasing)
        self.ui.chart_view.chart().setTheme(QtChart.QChart.ChartTheme.ChartThemeDark)
        sizePolicy = QSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
        sizePolicy.setHeightForWidth(self.ui.chart_view.sizePolicy().hasHeightForWidth())
        self.ui.chart_view.setSizePolicy(sizePolicy)

        self.ui.chart_view.setMinimumSize((QSize(0, 300)))
        self.ui.gridLayout_3.addWidget(self.ui.chart_view)
        self.ui.frame_19.setStyleSheet(u"background-color: transparent")

    def create_temp_chart(self):
        if not self.fileName:
            return
        low = QtChart.QBarSet("min")
        high = QtChart.QBarSet("max")
        ltemp = []
        htemp = []

        with open(self.fileName) as csvfile:
            csvreader = csv.reader(csvfile, delimiter=',')
            header_found = False
            for row in csvreader:
                if row[0] == "MinTemp":
                    header_found = True
                    continue
                if header_found:
                    ltemp.append(float(row[0]))
                    htemp.append(float(row[1]))
                if len(ltemp) >= 12:
                    break  # Asumiendo que uno solo requiere los primeros 12 meses de data
        low.append(ltemp)
        high.append(htemp)

        series = QtChart.QStackedBarSeries()
        series.append(low)
        series.append(high)

        chart = QtChart.QChart()
        chart.addSeries(series)
        chart.setTitle("Muestra de Temperatura en Celsius")
        chart.setAnimationOptions(QtChart.QChart.AnimationOption.SeriesAnimations)

        category = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

        axisX = QtChart.QBarCategoryAxis()
        axisX.append(category)
        axisX.setTitleText("Mes")
        chart.addAxis(axisX, Qt.AlignmentFlag.AlignBottom)
        axisY = QtChart.QValueAxis()
        axisY.setRange(-52, 52)
        axisY.setTitleText("Temperatura en Celsius")
        chart.addAxis(axisY, Qt.AlignmentFlag.AlignLeft)
        series.attachAxis(axisX)
        series.attachAxis(axisY)

        self.ui.chart_view = QtChart.QChartView(chart)
        self.ui.chart_view.setRenderHint(QPainter.RenderHint.Antialiasing)
        self.ui.chart_view.chart().setTheme(QtChart.QChart.ChartTheme.ChartThemeDark)
        sizePolicy = QSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
        sizePolicy.setHeightForWidth(self.ui.chart_view.sizePolicy().hasHeightForWidth())
        self.ui.chart_view.setSizePolicy(sizePolicy)

        self.ui.gridLayout_2.addWidget(self.ui.chart_view)
        self.ui.frame_18.setStyleSheet(u"background-color: transparent")

For an example, this is how it looks like:

I have a sample code that acts for printing but I’m not sure if textEdit will work to show the graphs. Here’s the code I have for the printer:

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QWidget
from PyQt5.QtPrintSupport import QPrinter, QPrintPreviewDialog, QPrintDialog

class print_UI(QWidget):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(521, 384)
        self.verticalLayout_2 = QtWidgets.QVBoxLayout(Form)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.textEdit = QtWidgets.QTextEdit(Form)
        self.textEdit.setObjectName("textEdit")
        self.verticalLayout.addWidget(self.textEdit)
        self.verticalLayout_2.addLayout(self.verticalLayout)
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.pushButton = QtWidgets.QPushButton(Form)
        self.pushButton.setObjectName("pushButton")
        self.pushButton.clicked.connect(self.print_file)
        self.horizontalLayout.addWidget(self.pushButton)
        self.pushButton_2 = QtWidgets.QPushButton(Form)
        self.pushButton_2.setObjectName("pushButton_2")
        self.pushButton_2.clicked.connect(self.print_preview_dialog)
        self.horizontalLayout.addWidget(self.pushButton_2)
        self.verticalLayout_2.addLayout(self.horizontalLayout)

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.pushButton.setText(_translate("Form", "Print Document"))
        self.pushButton_2.setText(_translate("Form", "Print Preview"))
    def print_file(self):
        printer = QPrinter(QPrinter.PrinterMode.HighResolution)
        dialog = QPrintDialog(printer,self)
        
        if dialog.exec_() == QPrintDialog.accepted:
            self.textEdit.print_(printer)
    def print_preview(self, printer):
        self.textEdit.print_(printer)
    def print_preview_dialog(self):
        printer = QPrinter(QPrinter.PrinterMode.HighResolution)
        previewDialog = QPrintPreviewDialog(printer, self)
        previewDialog.paintRequested.connect(self.print_preview)
        previewDialog.exec()
    
    


if __name__ == "__main__":
    import sys
    appi = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    uip = print_UI()
    uip.setupUi(Form)
    Form.show()
    sys.exit(appi.exec_())

Well, did you try it?

Sometimes we just have to use Search. A Youtube search limiting to the past year didn’t pull up anything obvious.

  1. Web search search for all times
  2. Web search for sites only in the past year.
  3. Gemini AI answer gave me nothing that was about printing. Be careful using AI. I have personally found that sometimes the answers work, sometimes they get the code from a very old post and it doesn’t work.
  4. If you don’t get help here ask on https://stackoverflow.com

Alternatives:

  1. Save the graph as an image file and open the image file with the default OS app and print with that app.
  2. I know this isn’t an ideal choice but have the user take a screen shot with Lightshot and print that. It has a direct to print feature but images can also be saved, annotated, copied to clipboard. And it covers all windows in the OS not just in the browser. But it’s just for Mac and Windows it seems.

Yeah, the code works, but it’s only used to write on a text textEdit form. My goal is that the graphs generated in propiedadesmain.py can be shown on the document, perhaps with some additional text as well, probably mentioning the kind of graph it is and the date that it was generated. However, every time I tried to find an alternative to add in those graphs (such as turning them into images), it always turns out wrong, usually the images being way too small.