Qt Webengine Render to Print

2019-06-22 09:22发布

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.

2条回答
姐就是有狂的资本
2楼-- · 2019-06-22 10:11

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?

查看更多
Anthone
3楼-- · 2019-06-22 10:12

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
}
查看更多
登录 后发表回答