user5647258
user5647258

Reputation:

Qt Webengine Render to Print

Is there any way to render HTML/SVG to printer, PDF, and raster images with QtWebEngine?

We want to switch from WebKit to WebEngine, so using WebKit's QWebView is not an option anymore.

Upvotes: 5

Views: 4172

Answers (2)

Johannes Munk
Johannes Munk

Reputation: 305

It took a bit of tinkering to get printing callable from a worker-thread:

void printToPDF(const QString& html, const QString& fileName)
{
    #if QT_VERSION >= 0x057000
    QtWebEngine::initialize();
    QWebEnginePage page;
    QEventLoop loop;
    loop.connect(&page, &QWebEnginePage::loadFinished, [&page, &loop, &fileName]() {
        page.printToPdf([&loop, &fileName] (QByteArray ba) {
            QFile f(fileName);
            if (f.open(QIODevice::WriteOnly))
            {
                f.write(ba);
                f.close();
            } else {
                qDebug() << "Error opening file for writing" << fileName << f.errorString();
            }
            loop.exit();
        });
    });
    page.setHtml(html);
    loop.exec();
    #endif
}

Upvotes: 1

demonplus
demonplus

Reputation: 5801

It is announced that Qt Web Engine will support printing to PDF in Qt 5.7 which is in beta now.

Two overloads of printToPdf() function were added in Qt 5.7 for QWebEnginePage class.

We have example how to use these new functions in our company blog.

You can look for some already available Qt Web Engine printing options also here:

QWebEngine: print a page?

Upvotes: 1

Related Questions