[EN] Rendering DPI in Qt’s WebKit


Some time ago, I stuck on reading manuals trying to find correct and clear way to enlarge DPI of images rendered by WebKit (in Qt).

If you need to render HTML page in your Qt app, you can use widgets that use QTextDocument, such as QLabel and QTextEdit. But all of them support limited subset of HTML 4 and CSS 2.1 (Qt Project — Supported HTML Subset). But if you need to use some more complicated things (or even some typical CSS styles) excluded from that list, you should use WebKit (WebKit in Qt).

To include the definitions of the module’s classes, use the following directive:

#include <QtWebKit>

To link against the module, add this line to your qmake .pro-file:

QT += webkit

This actions finish up by need to deploy corresponding lib, but as result — we can use sweet WebKit’s render.

The easiest way to render content is through the QWebView class. As a widget it can be embedded into your forms or a graphics view and it provides convenience functions for downloading and rendering web sites.

QWebView *view = new QWebView(parent);
view->render(&painter); // where QPainter painter;

As a result I got image on painter, but that image has — 96 dpi. So, to get picture of arbitrary dpi, we can ask WebKit to zoom page in (text and images respectively), set needed size and then render.

I got it work with printer this way:

void AppManager::onPrintRequested(QPrinter *printer)
    static QWebView w; // our renderer

    // configuring printer
    printer->setResolution(200); // real dpi of output image
    printer->setPageMargins(30, 20, 15, 20, 
    // setting size of rendered image
    w.resize( printer->paperRect().size() ); 
    // count new zoom factor to fit concrete dpi
    // (for example as my printer has) 
    qreal newZoomFactor = printer->resolution() / 96.0f; 
    // apply zoom

    QPainter painter(printer);
    painter.setRenderHint(QPainter::Antialiasing, true);
    painter.setRenderHint(QPainter::TextAntialiasing, true);

    QString htmlContent;
    // ...

    printer->newPage(); // if needed

Send feedback

Заповніть поля нижче або авторизуйтесь клікнувши по іконці

Лого WordPress.com

Ви коментуєте, використовуючи свій обліковий запис WordPress.com. Log Out / Змінити )

Twitter picture

Ви коментуєте, використовуючи свій обліковий запис Twitter. Log Out / Змінити )

Facebook photo

Ви коментуєте, використовуючи свій обліковий запис Facebook. Log Out / Змінити )

Google+ photo

Ви коментуєте, використовуючи свій обліковий запис Google+. Log Out / Змінити )

З’єднання з %s