Print the contents of QWebFrame with header and footer

1k Views Asked by At

I want to print a QWebView with a header and a footer. I'm using the class QPrintPreviewDialog to preview the print. I saw how solve this issue the projects phantomjs and wkhtmltopdf but it seems a little excessive the need to include in my project a modified version of WebKit. Apparentyly printing headers and footers with Qt and Webkit it's an issue not enterely solved:

  1. https://bugs.webkit.org/show_bug.cgi?id=30357
  2. https://bugreports.qt.io/browse/QTBUG-29619
  3. https://wiki.qt.io/Qt_project_org_faq (Question 229)

A priori I don't know how many pages I am going to print. Currently I am subclassing QPrinter and reimplementing the newPage() method. It's an awful hack but nearly works. The issue i'm facing is that everything that it is printed outside the pageRect it is shown like blurred. The watermark effect is only present in the preview not in the printed result, but the low quaility is present always.

There is something i can do to print headers with better quality, without bring all WebKit to my project?.

The difference that I suspect is introducing the problem is that I use QWebView::render instead of QWebView::print. QCustomPrinter has an associated QPainter before printing the header ( the QPainter associated when the content was printed ). Therefore I can't invoke QWebVieww:print when printing the headers because that method tries to associate a new QPainter to QPrinter.

void CustomPrinter::printHeader()
{
   QPainter & painter =*this->paintEngine()->painter();
   QWebView v;
   v.setContent("<html> "         
                "<body>"
                " asdadasdasdasd "
               "</body>"
              "</html>");
   v.setFixedSize(this->pageRect().size());
   v.render(&painter,QPoint(0,-  95),QRegion(0,0,this->pageRect().width(),95));
}

EDIT (based on Kuba Ober answer): Using QTextDocument instead of QWebView solves the quality issue.

void CustomPrinter::printHeader()
{
   QPainter * painter =p->paintEngine()->painter();
   painter->save();
   QTextDocument v;
   v.setHtml(QString::fromStdString(_impresion.cabecera()));
   QRectF r =this->pageRect();
   r.moveTo(0,0);
   r.setHeight(95);
   painter->translate(0,-95);
   v.drawContents(painter,r);
   painter->restore();
}

I share a minimun example of what i'm talking about. The CustomPrinter class prints the header. https://www.dropbox.com/s/2vifzk8rs6scrx5/stackExample.tar.gz?dl=0

0

There are 0 best solutions below