Qt Webengine Render to Print

痴心易碎 提交于 2020-01-03 11:50:33

问题


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.


回答1:


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?




回答2:


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
}


来源:https://stackoverflow.com/questions/36600722/qt-webengine-render-to-print

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!