Question

Well I'm trying to print a QWebView with multiple pages, using CSS page-break attribute, which works fine with WebKit. I'm using Qt 5.1.1.

My main problem is that everything is fine when I'm printing it as a PDF using Qt, but when I'm trying to actually print it to a real printer, then all pages but the first one are blank! Here is my (stripped) test's code :

Test.h :

class MainWindow : public QMainWindow, private Ui::MainWindow
{  
Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);

public slots:
    void printHTML();
    void printPreview(QPrinter *printer);
private:
    QWebView webView;
};

Test.cpp :

#include "Test.h"

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
    QString html;
    html= "<!DOCTYPE html><html>  <head>    <meta http-equiv='content-type' content='text/html;charset=UTF-8' />    <title>Paginated HTML</title>    <style type='text/css' media='print'>      div.page      {        page-break-after: always;        page-break-inside: avoid;      }    </style>  </head>  <body>    <div class='page'>      <h1>This is Page 1</h1>    </div>    <div class='page'>      <h1>This is Page 2</h1>    </div>    <div class='page'>      <h1>This is Page 3</h1>    </div>  </body></html>";

    webView.setHtml(html);
    printHTML();
}

void MainWindow::printPreview(QPrinter *printer) 
{
   webView.print(printer);
}

void MainWindow::printHTML() 
{
    QPrinter printer;
    QPrintPreviewDialog preview(&printer);
    preview.setWindowTitle("Test imp");

    connect(&preview, SIGNAL(paintRequested(QPrinter*)), this, SLOT(printPreview(QPrinter*)));

    preview.exec();

    this->close();
}

I've embed an HTML example as a string, this example works fine with any other WebKit engine and prints well.

The preview will display it as it should print, and when you actually print it using the print button of the preview, it will print the first page without any problem but then all remaining pages will be totally empty, blank.

I wasn't able to find any workaround, using a QPainter to render it is out of the question, since I need to have multiple pages and a QPainter isn't really a good way to manage multiple pages (at least I don't know how if it's able to : I never saw any QPainter manage multiple pages after rendering.)

PS : try it yourself, adding a

    printer.setOutputFormat(QPrinter::PdfFormat);

just after the QPrinter declaration works fine, it's saving as a PDF and get displayed with every pages printed out nicely. Which is a problem, since I need to print to a normal printer and would like to avoid saving as pdf and then printing the PDF.

Was it helpful?

Solution

This has never been corrected in Qt, but now QWebView have been replaced by QWebEngine and it does not suffer from these problems when printing its pages.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top