qmlprinter.cpp 11.9 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"

Michael Winkelmann's avatar
Michael Winkelmann committed
11 12 13 14 15
#include <QAbstractTextDocumentLayout>
#include <QPainter>
#include <QPrinter>
#include <QQuickItem>
#include <QQuickWindow>
16
#include <QtMath>
17

Michael Winkelmann's avatar
Michael Winkelmann committed
18
QmlPrinter::QmlPrinter() {}
19

20
QmlPrinter::~QmlPrinter() {}
21

Michael Winkelmann's avatar
Michael Winkelmann committed
22 23 24 25 26 27
void QmlPrinter::changePrinterOrientation(QPrinter &printer, const int &width,
                                          const int &height) {
  if (width > height)
    printer.setOrientation(QPrinter::Landscape);
  else
    printer.setOrientation(QPrinter::Portrait);
28
}
29

Michael Winkelmann's avatar
Michael Winkelmann committed
30 31 32 33 34
bool QmlPrinter::printPdf(const QString &location, QQuickItem *presentation) {
  QVector<QQuickItem *> slides, masterSlideElements;
  presentation->setProperty(
      "allowDelay",
      QVariant(false)); // Disable partial reveals on slide pages
35

Michael Winkelmann's avatar
Michael Winkelmann committed
36 37 38 39 40
  for (auto &item : presentation->childItems()) {
    if (item->property("isMaster").toBool()) {
      masterSlideElements.push_back(item);
    } else {
        if (item->metaObject()->className() != QStringLiteral("QQuickRepeater"))
41 42
            slides.push_back(item);
    }
Michael Winkelmann's avatar
Michael Winkelmann committed
43
  }
44

Michael Winkelmann's avatar
Michael Winkelmann committed
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
  if (slides.length() == 0) {
    return false;
  }

  auto width = presentation->property("width").toInt();
  auto height = presentation->property("height").toInt();

  QPrinter printer;
  printer.setOutputFormat(QPrinter::PdfFormat);
  printer.setOutputFileName(location);
  printer.setFullPage(true);
  printer.setPageLayout(QPageLayout(QPageSize(QSize(height, width)),
                                    QPageLayout::Portrait,
                                    QMarginsF(0, 0, 0, 0), QPageLayout::Pica));
  printer.setResolution(72);

  // Change the printer orientation based on the presentation
  // 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, width, height);

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

Michael Winkelmann's avatar
Michael Winkelmann committed
73 74
  for (int i = 0; i < slides.length(); ++i) {
    QQuickItem *pageObject = slides.at(i);
75

Michael Winkelmann's avatar
Michael Winkelmann committed
76 77 78 79
    // Paint master slide elements
    for (auto &masterSlideElement : masterSlideElements) {
      masterSlideElement->setProperty("slideNumber",i+1);
      paintItem(masterSlideElement, pageObject->window(), &painter);
80
    }
81

Michael Winkelmann's avatar
Michael Winkelmann committed
82 83 84 85 86 87 88 89 90 91 92
    // Paint current slide
    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 < slides.length()) {
      changePrinterOrientation(printer,
                               int(slides.at(next)->width()),
                               int(slides.at(next)->height()));
      printer.newPage();
93
    }
Michael Winkelmann's avatar
Michael Winkelmann committed
94
  }
95

Michael Winkelmann's avatar
Michael Winkelmann committed
96
  return true;
97 98
}

Michael Winkelmann's avatar
Michael Winkelmann committed
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
void QmlPrinter::paintItem(QQuickItem *item, QQuickWindow *window,
                           QPainter *painter) {
  if (!item || !item->isVisible())
    return;

  bool drawChildren = true;

  painter->save();
  painter->setMatrix(transformMatrix(item));
  painter->setMatrixEnabled(true);
  if (item->clip()) {
    painter->setClipping(true);
    painter->setClipRect(item->clipRect());
  }

  // 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);
126
        }
Michael Winkelmann's avatar
Michael Winkelmann committed
127 128 129
      }
    }
  } else if (isCustomPrintItem(item->metaObject()->className())) {
130

Michael Winkelmann's avatar
Michael Winkelmann committed
131 132 133 134 135 136
    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);
137

Michael Winkelmann's avatar
Michael Winkelmann committed
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
    const QRect rect(0,0,int(item->width()),int(item->height()));
    QImage image = window->grabWindow();
    painter->drawImage(0, 0, image, 0, 0, rect.width(), rect.height());
    painter->restore();
    drawChildren = false;
  } else if (item->flags().testFlag(QQuickItem::ItemHasContents)) {

    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) {
157
        QImage image = window->grabWindow();
158

Michael Winkelmann's avatar
Michael Winkelmann committed
159 160 161 162 163
        painter->drawImage(
            rect, image,
            QRect(rect.x(), rect.y(), rect.width(), rect.height()));
      }
      drawChildren = false;
164
    }
Michael Winkelmann's avatar
Michael Winkelmann committed
165 166
  }
  if (drawChildren) {
167

Michael Winkelmann's avatar
Michael Winkelmann committed
168 169 170 171
    auto items = item->childItems();
    std::sort(items.begin(), items.end(), [](QQuickItem *lhs, QQuickItem *rhs) {
      return lhs->z() < rhs->z();
    });
172

Michael Winkelmann's avatar
Michael Winkelmann committed
173 174 175
    for (auto item : items)
      paintItem(item, window, painter);
  }
176

Michael Winkelmann's avatar
Michael Winkelmann committed
177
  painter->restore();
178 179
}

Michael Winkelmann's avatar
Michael Winkelmann committed
180 181 182 183 184
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;
185

Michael Winkelmann's avatar
Michael Winkelmann committed
186 187 188
  const QRect rect(0, 0, int(item->width()), int(item->height()));
  QImage image = window->grabWindow();
  painter->drawImage(0, 0, image, 0, 0, rect.width(), rect.height());
189 190
}

Michael Winkelmann's avatar
Michael Winkelmann committed
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
void QmlPrinter::paintQQuickRectangle(QQuickItem *item, QPainter *painter) {
  const QRectF rect(0, 0, item->width(), item->height());

  const QColor color = item->property("color").value<QColor>();
  const QObject *border = item->property("border").value<QObject *>();
  const qreal borderWidth = border->property("width").value<qreal>();
  const QColor borderColor = border->property("color").value<QColor>();
  const qreal radius = item->property("radius").value<qreal>();
  const qreal opacity = item->property("opacity").value<qreal>();

  painter->setBrush(color);
  painter->setOpacity(opacity);

  if (borderWidth > 0.0 && !(borderWidth == 1.0 && borderColor == QColor(Qt::black))) {
    painter->setPen(QPen(borderColor, borderWidth));
  } else {
    painter->setPen(Qt::NoPen);
  }

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

Michael Winkelmann's avatar
Michael Winkelmann committed
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
void QmlPrinter::paintQQuickText(QQuickItem *item, QPainter *painter) {
  const QRectF rect(0, 0, item->width(), item->height());
  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(
      static_cast<Qt::Alignment>(horizontalAlignment | verticalAlignment));

  QFontMetrics fm(font);

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

  QTextDocument document;
  document.setPageSize(item->size());
  document.setDocumentMargin(0.0);
  document.setUseDesignMetrics(true);
  document.setTextWidth(rect.width());
  document.setDefaultTextOption(textOption);
  document.setDefaultFont(font);

  if (textFormat == Qt::PlainText)
    document.setPlainText(text);
  else
    document.setHtml(text);

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

  QAbstractTextDocumentLayout *layout = document.documentLayout();
  painter->translate(rect.topLeft());
  painter->setRenderHint(QPainter::Antialiasing, true);
  layout->draw(painter, context);
}
262

Michael Winkelmann's avatar
Michael Winkelmann committed
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
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());

  QRectF rect(0, 0, item->width(), item->height());
  QRectF sourceRect(0, 0, image.width(), image.height());

  switch (fillMode) {
  default:
    qWarning() << "QuickItemPainter::paintQuickImage unimplemented fill mode: "
               << fillMode;
    break;
  case 0: // Image.Stretch
    break;
  case 1: { // Image.PreserveAspectFit
    QSizeF 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());
288
    }
Michael Winkelmann's avatar
Michael Winkelmann committed
289 290 291 292 293 294 295 296
    if (sourceRect.height() > rect.height()) {
      rect.setHeight(sourceRect.height());
    } else {
      sourceRect.setHeight(rect.height());
    }
  } break;
  }
  painter->drawImage(rect, image, sourceRect);
297 298
}

Michael Winkelmann's avatar
Michael Winkelmann committed
299 300 301 302 303 304 305
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;
306 307
}

Michael Winkelmann's avatar
Michael Winkelmann committed
308 309
void QmlPrinter::addPrintableItem(const QString &item) {
  printableItems.push_back(item);
310
}
311

Michael Winkelmann's avatar
Michael Winkelmann committed
312 313 314 315 316 317 318 319
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;
320 321
}

Michael Winkelmann's avatar
Michael Winkelmann committed
322 323 324 325 326 327 328 329 330 331 332 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
QMatrix QmlPrinter::transformMatrix(QQuickItem *item) {

  QTransform t;
  if (item->parentItem())
    t = QTransform(transformMatrix(item->parentItem()));

  t.translate(item->x(), item->y());

  auto transforms = item->transform();
  auto tCount = transforms.count(&transforms);

  if (!tCount) {
    QMatrix4x4 m(t);
    for (int ii = tCount - 1; ii >= 0; --ii)
      transforms.at(&transforms, ii)->applyTo(&m);
    t = m.toTransform();
  }

  auto computeTransformOrigin = [](QQuickItem *item) {
    switch (item->transformOrigin()) {
    case QQuickItem::TopLeft:
      return QPointF(0, 0);
    case QQuickItem::Top:
      return QPointF(item->width() / 2., 0);
    case QQuickItem::TopRight:
      return QPointF(item->width(), 0);
    case QQuickItem::Left:
      return QPointF(0, item->height() / 2.);
    case QQuickItem::Center:
      return QPointF(item->width() / 2., item->height() / 2.);
    case QQuickItem::Right:
      return QPointF(item->width(), item->height() / 2.);
    case QQuickItem::BottomLeft:
      return QPointF(0, item->height());
    case QQuickItem::Bottom:
      return QPointF(item->width() / 2., item->height());
    case QQuickItem::BottomRight:
      return QPointF(item->width(), item->height());
360
    }
Michael Winkelmann's avatar
Michael Winkelmann committed
361 362 363 364 365 366 367 368 369 370 371 372
    return QPointF(0.0,0.0);
  };

  if (item->scale() != 1. || item->rotation() != 0.) {
    QPointF tp = computeTransformOrigin(item);
    t.translate(tp.x(), tp.y());
    t.scale(item->scale(), item->scale());
    t.rotate(item->rotation());
    t.translate(-tp.x(), -tp.y());
  }

  return t.toAffine();
373
}