10

The migration from QWebKit to QWebEngine seems to be much more complicated than Qt guys claimed. With QWebKit I could print a webpage easily via

QWebView->print(&printer);

With QWebEngine class QWebEngine view does not provide a method print(). Their browser example uses a class named QWebEngineFrame which offers a method print() - but the whole QWebEngineFrame is not defined anywhere!

So my question: how do I print a page using QWebEngine?

Andrew Komiagin
  • 6,446
  • 1
  • 13
  • 23
Elmi
  • 5,899
  • 15
  • 72
  • 143

4 Answers4

10

I think the correct way to use QWebEngineView::render method because QWebEngineView is a QWidget. It accepts paint device as a first argument and you may pass QPrinter there for printing.

Update: If you can use the latest version of Qt, in Qt 5.8 a new function for printing page was added:

void QWebEnginePage::print(QPrinter *printer, FunctorOrLambda resultCallback);

Actually it first prints to temp PDF with QPrinter settings.

Here is the link to Qt docs.

You can read about this in our blog also.

m7913d
  • 10,244
  • 7
  • 28
  • 56
demonplus
  • 5,613
  • 12
  • 49
  • 68
  • 1
    This is not really a solution - try to print a page which is larger than what can be displayed visibly and you wil understand where the limits are ;-) – Elmi May 01 '16 at 15:26
3

I would offer following code (for a while):

    QTextEdit *textEdit = new QTextEdit;
    ui.myWebView->page()->toHtml([textEdit](const QString &result){ textEdit->setHtml(result); });
    textEdit->print(somerinter);
    textEdit->deleteLater();
eSKon
  • 439
  • 3
  • 6
  • Thanks! This works fine for simple printing of some HTML: `QTextEdit *textEdit = new QTextEdit; textEdit->setHtml(td.toHtml()); textEdit->print(_printer); textEdit->deleteLater();` where td is a QTextDocument. – Marc Jul 26 '16 at 14:42
2

Qt 5.7 includes print support in to pdf files for QWebEngine.

Use printToPdf function to export the current page in a pdf file. Example:

const QString fileName = QFileDialog::getSaveFileName(0,
                                                tr("Save pdf"),
                                                ".",
                                                tr("PDF Files (*.pdf)"));
if (fileName.isEmpty()) {
    return;
}
ui->webView->page()->printToPdf(fileName);
mohabouje
  • 3,867
  • 2
  • 14
  • 28
  • 1
    It should be noted that the printToPdf() method adds static text "PAGE 2:" to the top of the 2nd page, and so on, and this is not configurable. Additionally, there is no way to add custom headers/footers to each page. If these two things don't bother you, it's a great simple solution and works even when the document spans multiple pages. – Vern Jensen May 25 '17 at 00:22
1

QWebView->page()->print(&printer, [=](bool){});