简体   繁体   中英

PyQt5 save Textedit to image

I would like to save Qtexedit's text to a image preferable a PNG.

i read in thread Rich text to image in Qt by Dmitry Sazonov

it can maybe be done using QTextEdit::document QTextDocument::drawContents

However i do not find any examples out there.

The first thing you must do is create a QPixmap with an appropriate size, fill it with some background color, then create a QPainter , this will be responsible for drawing on the QPixmap , we use drawContents() to draw, we finish the painting with end() , at the end we save it with the save() function of QPixmap .

Example:

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

html = """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Cantarell'; font-size:11pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Open Sans,Arial,sans-serif'; font-size:14px; font-style:italic; color:#000000; background-color:#ffffff;">Lorem ipsum</span><span style=" font-family:'Open Sans,Arial,sans-serif'; font-size:14px; color:#000000; background-color:#ffffff;"> dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </span><span style=" font-family:'Open Sans,Arial,sans-serif'; font-size:14px; font-weight:600; color:#000000; background-color:#ffffff;">Duis aute irure dolor</span><span style=" font-family:'Open Sans,Arial,sans-serif'; font-size:14px; color:#000000; background-color:#ffffff;"> in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, </span><span style=" font-family:'Open Sans,Arial,sans-serif'; font-size:14px; text-decoration: underline; color:#000000; background-color:#ffffff;">sunt in culpa qui officia deserunt mollit anim id est laborum.</span></p>
<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Open Sans,Arial,sans-serif'; font-size:14px; text-decoration: underline; color:#000000;"><br /></p>
<p align="center" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Open Sans,Arial,sans-serif'; font-size:14px; color:#000000; background-color:#ffffff;">Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?</span></p></body></html>"""


def save(doc):
    pixmap = QPixmap(doc.idealWidth(), doc.size().height())
    pixmap.fill(Qt.white)
    painter = QPainter(pixmap)
    doc.drawContents(painter, QRectF(0, 0, doc.idealWidth(),  doc.size().height()))
    painter.end()
    pixmap.save("output.png", "PNG")

if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    w = QWidget()

    lay = QVBoxLayout(w)

    btn = QPushButton("Save")
    te = QTextEdit()

    lay.addWidget(btn)
    lay.addWidget(te)

    te.setHtml(html)

    w.show()
    btn.clicked.connect(lambda checked, doc=te.document(): save(doc))

    sys.exit(app.exec_())

GUI

在此处输入图片说明

PNG

在此处输入图片说明

Plus:

If you want to invert the colors of each pixel, it would be more appropriate to use QImage :

def save(doc):
    image = QImage(doc.idealWidth(), doc.size().height(), QImage.Format_RGB32)
    image.fill(Qt.white)
    painter = QPainter(image)
    doc.drawContents(painter, QRectF(0, 0, doc.idealWidth(),  doc.size().height()))
    painter.end()
    image.invertPixels(QImage.InvertRgb)
    image.save("output.png", "PNG")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM