Qt 将 widget 打印到 pdf

一开始直接render到QPrinter里发现渲染出的图很小,原因是没有把两者的尺寸对齐到一致
这里我们按printer和widget的比例缩放:

def exportToPDF(w : QWidget, file_name):
        printer = QPrinter()
        printer.setPageSize(QPrinter.A4)
        printer.setOutputFormat(QPrinter.PdfFormat)
        printer.setOutputFileName(file_name)

        painter = QPainter(printer)
        xscale = printer.pageRect().width() / w.width()
        yscale = printer.pageRect().height() / w.height()
        scale = min(xscale, yscale)
        painter.scale(scale, scale)
        margin = 5
        w.render(painter, QPoint(margin, margin))
        painter.end()
posted @ 2023-04-24 11:03  miyanyan  阅读(380)  评论(0编辑  收藏  举报