5

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.

  • You can still use QWebView::print(). QtWebEngine does not supports printing yet (Qt 5.6) – Archie Apr 13 '16 at 14:05
  • Well, depending in the HTML support required, you may try QTextDocument, since it has some limited HTML support, but can be good enough (http://doc.qt.io/qt-5/richtext-html-subset.html) – Archie Apr 13 '16 at 14:17

2 Answers2

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?

Community
  • 1
  • 1
demonplus
  • 5,613
  • 12
  • 49
  • 68
  • But there is still no way to print to a print dialog/real printer & paper' – swaechter Jul 06 '16 at 12:38
  • @swaechter Yes, unfortunately there is no idea when this will be implemented, see [here](https://trello.com/c/JE5kosmC/72-printing-support) – demonplus Jul 06 '16 at 13:47
  • I really like Qt, but that's just lame (Think about all the business customers that have to print their invoices/bills/reports in their application etc). I guess I'll print it to PDF and use poppler for rendering/printing – swaechter Jul 06 '16 at 14:22
1

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
}
Johannes Munk
  • 305
  • 2
  • 8