qmlprinter.cpp 10.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/*
 * 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"

QmlPrinter::QmlPrinter(QObject *parent) :
    QObject(parent)
{
}

QmlPrinter::~QmlPrinter()
{

}

void QmlPrinter::printPDF(const QString &location, QQuickItem *item, bool showPDF)
{
23 24 25
    if(!item)
        return;

26 27 28 29 30 31 32 33 34 35
    QPrinter printer;
    printer.setOutputFormat(QPrinter::PdfFormat);
    printer.setOutputFileName(location);
    printer.setFullPage(true);
    if(item->width() > item->height())
        printer.setOrientation(QPrinter::Landscape);
    else
        printer.setOrientation(QPrinter::Portrait);
    printer.setPaperSize(QPrinter::A4);

36 37 38 39
    // Resizes the root object to the resolution that the printer uses for printable area
    item->setProperty("width", printer.pageRect().width());
    item->setProperty("height", printer.pageRect().height());

40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
    QPainter painter;
    painter.begin(&printer);
    paintItem(item, item->window(), &painter);
    painter.end();

    if(showPDF) {
        QDesktopServices::openUrl(QUrl("file:///" + location));
    }
}

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

55
    bool drawChildren = true;
56 57 58 59 60 61 62 63 64 65 66
    if(isCustomPrintItem(item->metaObject()->className())) {
        painter->save();
        if(item->clip()) {
            painter->setClipping(true);
            painter->setClipRect(item->clipRect());
        }
        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());
        painter->restore();
67
        drawChildren = false;
68
    } else if(item->flags().testFlag(QQuickItem::ItemHasContents)) {
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
        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()));
            }
90
            drawChildren = false;
91 92 93
        }
        painter->restore();
    }
94 95 96 97 98
    if(drawChildren) {
        const QObjectList children = item->children();
        foreach(QObject *obj, children) {
            paintItem(qobject_cast<QQuickItem*>(obj), window, painter);
        }
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
    }
}

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>();

    painter->setBrush(color);

    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)
{
143
    const QRectF rect = item->mapRectToScene(item->boundingRect());
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 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 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
    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>();

    QTextOption textOption;
    textOption.setWrapMode(QTextOption::WrapMode(wrapMode));
    textOption.setAlignment((Qt::Alignment)(horizontalAlignment | verticalAlignment));



    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;
            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;
                double cosine = cos((double)item->rotation() * PI / 180.0);
                double sine = sin((double)item->rotation() * PI / 180.0);

                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);

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

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

            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: {
            QTextDocument doc;
            doc.setTextWidth(rect.width());
            doc.setDefaultTextOption(textOption);
            doc.setDefaultFont(font);

            doc.setHtml(text);

            QAbstractTextDocumentLayout::PaintContext context;

            context.palette.setColor(QPalette::Text, color);

            QAbstractTextDocumentLayout *layout = doc.documentLayout();
            painter->translate(rect.topLeft());
            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());

    QRect rect = item->mapRectToScene(item->boundingRect()).toRect(); // TODO should it be set on the QPainter ?
    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;
}
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326

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;
}