qmlprinter.cpp 16.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
/*
 * Copyright (c) 2014 Taneli Peltoniemi <taneli.peltoniemi@gmail.com>
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include "qmlprinter.h"

11 12
#include <QGraphicsView>

13 14 15 16 17 18 19 20 21 22
QmlPrinter::QmlPrinter(QObject *parent) :
    QObject(parent)
{
}

QmlPrinter::~QmlPrinter()
{

}

23
void QmlPrinter::changePrinterOrientation(QPrinter& printer, const int &width, const int &height)
24
{
25 26 27 28 29
    if(width > height)
        printer.setOrientation(QPrinter::Landscape);
    else
        printer.setOrientation(QPrinter::Portrait);
}
30

31 32 33 34 35
bool QmlPrinter::printPDF(const QString &location, QList<QQuickItem*> items, bool showPDF)
{
    if(items.length() == 0) {
        return false;
    }
36 37 38 39 40
    QPrinter printer;
    printer.setOutputFormat(QPrinter::PdfFormat);
    printer.setOutputFileName(location);
    printer.setFullPage(true);

41 42 43 44
    // Change the printer orientation based on the first page
    // This needs to be called before the painting is started as it will only take effect
    // after newPage is called (painter.begin() calls this method)
    changePrinterOrientation(printer, items.at(0)->width(), items.at(0)->height());
45

46
    QPainter painter;
47 48 49 50
    // It's possible to fail here for example if the file location does not allow writing
    if(!painter.begin(&printer)) {
        return false;
    }
51

52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
    for(int i = 0; i < items.length(); ++i) {
        QQuickItem *pageObject = items.at(i);
        // Change the page width/height to match what the printer gives us
        // This way all the components will be resized accordingly
        pageObject->setProperty("width", printer.pageRect().width());
        pageObject->setProperty("height", printer.pageRect().height());

        paintItem(pageObject, pageObject->window(), &painter);

        // We need to lookahead so we can setup the printer orientation for the next
        // item and add a new page to the printer
        int next = i + 1;
        if(next < items.length()) {
            changePrinterOrientation(printer, items.at(next)->width(), items.at(next)->height());
            printer.newPage();
        }
    }

    painter.end();
71 72 73
    if(showPDF) {
        QDesktopServices::openUrl(QUrl("file:///" + location));
    }
74
    return true;
75 76
}

77
bool QmlPrinter::print(const QPrinterInfo& info, QList<QQuickItem *> items)
78
{
79 80
    if(items.length() == 0)
        return false;
81 82

    QPrinter printer(info);
83
    //printer.setFullPage(true);
84

85 86 87 88
    // Change the printer orientation based on the first page
    // This needs to be called before the painting is started as it will only take effect
    // after newPage is called (painter.begin() calls this method)
    changePrinterOrientation(printer, items.at(0)->width(), items.at(0)->height());
89

90
    QPainter painter;
91

92 93 94 95 96
    if(!painter.begin(&printer)) {
        return false;
    }
    for(int i = 0; i < items.length(); ++i) {
        QQuickItem *pageObject = items.at(i);
97

98 99
        // Change the page width/height to match what the printer gives us
        // This way all the components will be resized accordingly
100

101 102
        int width = printer.pageRect().width();
        int height = printer.pageRect().height();
103

104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
        /*
        width -= (printer.pageLayout().margins().right() * 2);
        height -= (printer.pageLayout().margins().bottom() * 2);*/

        pageObject->setProperty("width", width);
        pageObject->setProperty("height", height);

        paintItem(pageObject, pageObject->window(), &painter);

        // We need to lookahead so we can setup the printer orientation for the next
        // item and add a new page to the printer
        int next = i + 1;
        if(next < items.length()) {
            changePrinterOrientation(printer, items.at(next)->width(), items.at(next)->height());
            printer.newPage();
        }
    }
121
    painter.end();
122
    return true;
123 124
}

125 126 127 128 129
void QmlPrinter::paintItem(QQuickItem *item, QQuickWindow *window, QPainter *painter)
{
    if(!item || !item->isVisible())
        return;

130
    bool drawChildren = true;
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148

    // This is a bit special case as we need to use childItems instead of children
    if(inherits(item->metaObject(), "QQuickListView")) {
        drawChildren = false;
        QList<QQuickItem*> childItems = item->childItems();
        if(childItems.length() > 0) {
            // First item is the QML ListView
            QQuickItem *listView = childItems.at(0);
            if(listView != nullptr) {
                // Draw the child items of the QML ListView
                QList<QQuickItem*> listViewChildren = listView->childItems();
                foreach(QQuickItem *children, listViewChildren) {
                    paintItem(children, window, painter);
                }
            }
        }
    }
    else if(isCustomPrintItem(item->metaObject()->className())) {
149 150 151 152 153 154
        painter->save();
        if(item->clip()) {
            painter->setClipping(true);
            painter->setClipRect(item->clipRect());
        }

155 156 157 158 159 160 161 162
        const int boundingMargin = 5;
        QRectF boundingRect;
        boundingRect.setTop(item->boundingRect().top() - boundingMargin);
        boundingRect.setLeft(item->boundingRect().left() - boundingMargin);
        boundingRect.setHeight(item->boundingRect().height() + boundingMargin * 2);
        boundingRect.setWidth(item->boundingRect().width() + boundingMargin * 2);

        const QRectF rect = item->mapRectToScene(boundingRect);
163 164 165
        QImage image = window->grabWindow();
        painter->drawImage(rect.x(), rect.y(), image, rect.x(), rect.y(), rect.width(), rect.height());
        painter->restore();
166
        drawChildren = false;
167
    } else if(item->flags().testFlag(QQuickItem::ItemHasContents)) {
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
        painter->save();
        if(item->clip()) {
            painter->setClipping(true);
            painter->setClipRect(item->clipRect());
        }
        if(inherits(item->metaObject(), "QQuickRectangle")) {
            paintQQuickRectangle(item, painter);
        } else if(inherits(item->metaObject(), "QQuickText")) {
            paintQQuickText(item, painter);
        } else if(inherits(item->metaObject(), "QQuickImage")) {
            paintQQuickImage(item, painter);
        } else if(inherits(item->metaObject(), "QQuickCanvasItem")) {
            paintQQuickCanvasItem(item, window, painter);
        } else {
            // Fallback to screen capture if we are unable to parse the data
            QRect rect = item->mapRectFromScene(item->boundingRect()).toRect();
            if(window != nullptr) {
                QImage image = window->grabWindow();

                painter->drawImage(rect, image, QRect(rect.x(), rect.y(), rect.width(), rect.height()));
            }
189
            drawChildren = false;
190 191 192
        }
        painter->restore();
    }
193 194 195 196 197
    if(drawChildren) {
        const QObjectList children = item->children();
        foreach(QObject *obj, children) {
            paintItem(qobject_cast<QQuickItem*>(obj), window, painter);
        }
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
    }
}

void QmlPrinter::paintQQuickCanvasItem(QQuickItem *item, QQuickWindow *window, QPainter *painter)
{
    // No point in continuing as we are unable to grab the image
    if(window == nullptr)
        return;

    const QRectF rect = item->mapRectToScene(item->boundingRect());

    QImage image = window->grabWindow();
    painter->drawImage(rect.x(), rect.y(), image, rect.x(), rect.y(), rect.width(), rect.height());


}

void QmlPrinter::paintQQuickRectangle(QQuickItem *item, QPainter *painter)
{
    const QRect rect = item->mapRectToScene(item->boundingRect()).toRect();
    const QColor color = item->property("color").value<QColor>();
    const QObject* border = item->property("border").value<QObject*>();
    const qreal border_width = border->property("width").value<qreal>();
    const QColor border_color = border->property("color").value<QColor>();
    const qreal radius = item->property("radius").value<qreal>();
223
    const qreal opacity = item->property("opacity").value<qreal>();
224 225

    painter->setBrush(color);
226
    painter->setOpacity(opacity);
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243

    if(border_width > 0 and not (border_width == 1 and border_color == QColor(Qt::black))) {
        painter->setPen(QPen(border_color, border_width));
    } else {
        painter->setPen(Qt::NoPen);
    }

    if(radius > 0) {
        painter->drawRoundedRect(rect, radius, radius);
    } else {
        painter->drawRect(rect);
    }

}

void QmlPrinter::paintQQuickText(QQuickItem *item, QPainter *painter)
{
244
    const QRectF rect = item->mapRectToScene(item->boundingRect());
245 246 247 248 249 250 251 252
    const QFont font = item->property("font").value<QFont>();
    const QString text = item->property("text").value<QString>();
    const QColor color = item->property("color").value<QColor>();
    const int wrapMode = item->property("wrapMode").value<int>();
    int textFormat = item->property("textFormat").value<int>();
    const int horizontalAlignment = item->property("horizontalAlignment").value<int>();
    const int verticalAlignment   = item->property("verticalAlignment").value<int>();

253 254 255
    const int elide = item->property("elide").value<int>();
    Qt::TextElideMode elideMode = static_cast<Qt::TextElideMode>(elide);

256 257
    QTextOption textOption;
    textOption.setWrapMode(QTextOption::WrapMode(wrapMode));
258
    textOption.setAlignment(static_cast<Qt::Alignment>(horizontalAlignment | verticalAlignment));
259

260
    QFontMetrics fm(font);
261 262 263 264 265 266 267 268 269 270 271

    if(textFormat == Qt::AutoText) {
        textFormat = Qt::mightBeRichText(text) ? 4 : Qt::PlainText;
    }

    switch (textFormat) {
        case Qt::PlainText: {
            painter->setFont(font);
            painter->setPen(color);

            QRectF textRect = rect;
272

273 274 275 276 277 278 279 280 281 282 283 284
            if(item->rotation() != 0) {
                int xc = rect.x() + rect.width() / 2;
                int yc = rect.y() + rect.height() / 2;

                QMatrix matrix;
                matrix.translate(xc, yc);
                matrix.rotate(item->rotation());

                painter->setMatrix(matrix);
                painter->setMatrixEnabled(true);

                double PI = 3.14159265358979323846;
285 286
                double cosine = cos(static_cast<double>(item->rotation()) * PI / 180.0);
                double sine = sin(static_cast<double>(item->rotation()) * PI / 180.0);
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301

                textRect = QRectF(-abs(sine) * rect.height() * 0.5,
                                  abs(cosine) * rect.width() * 0.5,
                                  rect.height(), rect.width());
            }
            bool fontModified;
            QTextLayout textLayout;
            textLayout.setFont(font);
            textLayout.setTextOption(textOption);
            QTextCharFormat defaultFormat;
            defaultFormat.setForeground(color);

            QList<StyledTextImgTag*> tags;
            StyledText::parse(text, textLayout, tags, QUrl(), qmlContext(item), true, &fontModified, defaultFormat);

302 303 304 305 306 307
            QString elidedText = textLayout.text();
            if(elideMode != Qt::ElideNone) {
                elidedText = fm.elidedText(elidedText, elideMode, item->width());
                textLayout.setText(elidedText);
            }

308 309
            textLayout.beginLayout();

310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
            switch(textOption.wrapMode()) {
            case QTextOption::NoWrap:
                textLayout.createLine();
                break;
            case QTextOption::WordWrap:
            case QTextOption::ManualWrap:
            case QTextOption::WrapAnywhere:
            case QTextOption::WrapAtWordBoundaryOrAnywhere: {
                int height = 0;
                forever {
                    QTextLine line = textLayout.createLine();
                    if(!line.isValid())
                        break;
                    line.setLineWidth(item->width());
                    line.setPosition(QPointF(0, height));
                    height += line.height();
                }
            } break;
            default:
                break;
330 331
            }

332
            textLayout.endLayout();
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
            textLayout.draw(painter, textRect.topLeft());

        } break;
        default:
        case 4: {
            bool fontModified;
            QTextLayout textLayout;
            textLayout.setFont(font);
            textLayout.setTextOption(textOption);
            QTextCharFormat defaultFormat;
            defaultFormat.setForeground(color);

            QList<StyledTextImgTag*> tags;
            StyledText::parse(text, textLayout, tags, QUrl(), qmlContext(item), true, &fontModified, defaultFormat);


            textLayout.beginLayout();
            int height = 0;
            const int leading = 0;
            while (1) {
                QTextLine line = textLayout.createLine();
                if (!line.isValid())
                    break;

                line.setLineWidth(item->width());
                height += leading;
                line.setPosition(QPointF(0, height));
                height += line.height();
            }
            textLayout.endLayout();

            painter->setRenderHint(QPainter::Antialiasing, true);
            textLayout.draw(painter, rect.topLeft());
        } break;
        case Qt::RichText: {
368 369 370 371
            QRectF textRect = rect;
            if(item->rotation() != 0) {
                int xc = rect.x() + rect.width() / 2;
                int yc = rect.y() + rect.height() / 2;
372

373 374 375
                QMatrix matrix;
                matrix.translate(xc, yc);
                matrix.rotate(item->rotation());
376

377 378 379 380 381 382
                painter->setMatrix(matrix);
                painter->setMatrixEnabled(true);

                double PI = 3.14159265358979323846;
                double cosine = cos(static_cast<double>(item->rotation()) * PI / 180.0);
                double sine = sin(static_cast<double>(item->rotation()) * PI / 180.0);
383

384 385 386 387 388 389 390 391 392 393 394 395
                textRect = QRectF(-abs(sine) * rect.height() * 0.5,
                                  abs(cosine) * rect.width() * 0.5,
                                  rect.height(), rect.width());
            }

            QTextDocument document;
            document.setTextWidth(textRect.width());
            document.setDefaultTextOption(textOption);
            document.setDefaultFont(font);
            document.setHtml(text);

            QAbstractTextDocumentLayout::PaintContext context;
396 397
            context.palette.setColor(QPalette::Text, color);

398 399
            QAbstractTextDocumentLayout *layout = document.documentLayout();
            painter->translate(textRect.topLeft());
400 401 402 403 404 405 406 407 408 409 410 411 412
            painter->setRenderHint(QPainter::Antialiasing, true);
            layout->draw(painter, context);
        } break;
    }
}

void QmlPrinter::paintQQuickImage(QQuickItem *item, QPainter *painter)
{
    const QUrl url = item->property("source").value<QUrl>();
    const int fillMode = item->property("fillMode").value<int>();

    QImage image(url.toLocalFile());

413
    QRect rect = item->mapRectToScene(item->boundingRect()).toRect();
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
    QRect sourceRect(0, 0, image.width(), image.height());

    switch(fillMode)
    {
        default:
            qWarning() << "QuickItemPainter::paintQuickImage unimplemented fill mode: " << fillMode;
        case 0: // Image.Stretch
            break;
        case 1: { // Image.PreserveAspectFit
            QSize size = sourceRect.size();
            size.scale(rect.width(), rect.height(), Qt::KeepAspectRatio);
        } break;
        case 6: { // Image.Pad
            if(sourceRect.width() > rect.width()) {
                rect.setWidth(sourceRect.width());
            } else {
                sourceRect.setWidth(rect.width());
            }
            if(sourceRect.height() > rect.height()){
                rect.setHeight(sourceRect.height());
            } else {
                sourceRect.setHeight(rect.height());
            }
        } break;
    }
    painter->drawImage(rect, image, sourceRect);
}

bool QmlPrinter::inherits(const QMetaObject *metaObject, const QString &name)
{
    if(metaObject->className() == name) {
        return true;
    } else if(metaObject->superClass()) {
        return inherits(metaObject->superClass(), name);
    }
    return false;
}
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466

void QmlPrinter::addPrintableItem(const QString &item)
{
    printableItems.push_back(item);
}

bool QmlPrinter::isCustomPrintItem(const QString &item)
{
    QListIterator<QString> it(printableItems);
    while(it.hasNext()) {
        QString printableItem = it.next();
        if(item.contains(printableItem))
            return true;
    }
    return false;
}