Wednesday, November 16, 2016

New print option for QtWebEngine in Qt 5.8

Beta version of Qt 5.8 version is out now and list of new features is available here .

For QWebEnginePage a new print option was added. As soon as in Qt 5.7 printing to PDF was already available, now printing through QPrinter also works:

void print(QPrinter *printer, 
       FunctorOrLambda resultCallback);

This is actually implemented by saving web content into temporary PDF file and then printing it out. When saving PDF file, settings of QPrinter are applied.

We can easily find an example of this function usage in demobrowser (Qt installation, Examples folder). resultCallback takes boolean as parameter which indicates whether printing is successful or not.

m_currentPrinter = new QPrinter();
QScopedPointer dialog(new QPrintDialog(m_currentPrinter, this));
dialog->setWindowTitle(tr("Print Document"));
if (dialog->exec() != QDialog::Accepted) {
    slotHandlePagePrinted(false);
    return;
}
page->print(m_currentPrinter, invoke(this, &BrowserMainWindow::slotHandlePagePrinted));
void BrowserMainWindow::slotHandlePagePrinted(bool result)
{
    Q_UNUSED(result);

    delete m_currentPrinter;
    m_currentPrinter = nullptr;
}