Exporting widgets and setting the position of to the top of the paper in pyqt5

I have a set of student information which I kept inside a QWidget. I created the following method to render() the QWidget and convert the QWidget content to pdf. Include is the output, positioned at the center

def print_widget(self, widget, filename):
    printer = QPrinter(QPrinter.HighResolution)
    painter = QPrinter(printer)
    xscale = printer.pageRect().width() * 1.0 / widget.width()
     yscale = printer.pageRect().height * 1.0 / widget.height()
    scale = min(xscale, yscale)
    painter.translate(printer.paperRect().center())#set as center here 
    painter.scale(scale, scale)
    painter.translate(-widget.width()/2, -widget.height()/2)
def pdfexport(self):
    fn, _ = QFileDialog.getSaveFileName(self, "Export PDF", None, "PDF files (.pdf);;All Files()")
    if fn:
        if QFileInfo(fn).suffix() == "":
            fn += ".pdf"
        self.print_widget(self.student_profiler, fn)

It worked well but I want it to position the widget at the top of the paper not at the centre. Thanks in anticipations

Hello hey, please someone should bail me out on this question, really need your help

Hey @meshelleva4815, sorry I missed this before. The centering is happening here, we can step through what you’re currently doing and see how to modify it.

painter.translate(printer.paperRect().center())   #1
painter.scale(scale, scale)  # 2
painter.translate(-widget.width()/2, -widget.height()/2)  # 3
  1. Translate coordinates to the center of the page, in both x & y
  2. Scale to fit to the page
  3. Translate back by half the width & height.

The first step would put the top left of the widget in the middle of the paper. So, then shifting back by half height, half width, puts the middle of the widget, in the middle of the paper.

To translate just the X position we can not translate the y to the middle of the page. We’ll end up with the top left of the widget being at the top of the page, in the middle (horizontally). The next translate can then just move the widget back horizontally to align on the middle.

I think the following should do it …

xshift = printer.paperRect().width() / 2
painter.translate(xshift, 0)   #1
painter.scale(scale, scale)  # 2
painter.translate(-widget.width()/2, 0)  # 3
  1. Translate to width/2 (the horizontal center), no change on vertical.
  2. Scale
  3. Translate back the width of the widget / 2, nothing on y.

Let me know if that works, can’t test just now but will have a look again tomorrow if not.

1 Like

That’s a relief, it worked just exactly as I wanted it. You doing a great with this time help you give boss. I hope to be like you some days boss. :hugs: