-1

I'm trying to print preview a PIL image using QPrintPreviewDialog() how can I do that?

1 Answers1

0

To convert a PIL image to a pixmap (so you can print it) you can use this function:

def pil2pixmap(im):
    if im.mode == "RGB":
        r, g, b = im.split()
        im = IM.merge("RGB", (b, g, r))
    elif im.mode == "RGBA":
        r, g, b, a = im.split()
        im = IM.merge("RGBA", (b, g, r, a))
    elif im.mode == "L":
        im = im.convert("RGBA")
    im2 = im.convert("RGBA")
    data = im2.tobytes("raw", "RGBA")
    qim = QtGui.QImage(data, im.size[0], im.size[1], QtGui.QImage.Format_ARGB32)
    qim = qim.smoothScaled(int(2480 / 3.2), int(3508 / 3.2))
    pixmap = QtGui.QPixmap.fromImage(qim)
    return pixmap

Source for the code above: https://stackoverflow.com/a/48705903/16592435

And then to preview an image you can use this function:

def print_image(image):
    
   # Initializes the QPainter and draws the pixmap onto it
    def drawImage(printer):
        painter = QPainter()
        painter.begin(printer)
        painter.setPen(Qt.red)
        painter.drawPixmap(0, 0, pil2pixmap(image))
        painter.end()
    
    # Shows the preview
    app = QApplication(sys.argv)
    dlg = QPrintPreviewDialog()
    dlg.paintRequested.connect(drawImage)
    dlg.exec_()
    app.exec_()