qmlprinter.cpp 10.6 KB
Newer Older
1 2
#include "qmlprinter.h"

3
#include <QLoggingCategory>
Michael Winkelmann's avatar
Michael Winkelmann committed
4 5 6 7 8
#include <QAbstractTextDocumentLayout>
#include <QPainter>
#include <QPrinter>
#include <QQuickItem>
#include <QQuickWindow>
9
#include <QtMath>
10

11 12
Q_LOGGING_CATEGORY(lc, "qt.qmlprinter")

Michael Winkelmann's avatar
Michael Winkelmann committed
13
QmlPrinter::QmlPrinter() {}
14

15
QmlPrinter::~QmlPrinter() {}
16

Michael Winkelmann's avatar
Michael Winkelmann committed
17 18 19 20 21 22
void QmlPrinter::changePrinterOrientation(QPrinter &printer, const int &width,
                                          const int &height) {
  if (width > height)
    printer.setOrientation(QPrinter::Landscape);
  else
    printer.setOrientation(QPrinter::Portrait);
23
}
24

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

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

Michael Winkelmann's avatar
Michael Winkelmann committed
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  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;
  }
67

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

Michael Winkelmann's avatar
Michael Winkelmann committed
71 72 73 74
    // Paint master slide elements
    for (auto &masterSlideElement : masterSlideElements) {
      masterSlideElement->setProperty("slideNumber",i+1);
      paintItem(masterSlideElement, pageObject->window(), &painter);
75
    }
76

Michael Winkelmann's avatar
Michael Winkelmann committed
77 78 79 80 81 82 83 84 85 86 87
    // 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();
88
    }
Michael Winkelmann's avatar
Michael Winkelmann committed
89
  }
90

Michael Winkelmann's avatar
Michael Winkelmann committed
91
  return true;
92 93
}

Michael Winkelmann's avatar
Michael Winkelmann committed
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
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();
Michael Winkelmann's avatar
Michael Winkelmann committed
119
        for (QQuickItem *children : listViewChildren) {
Michael Winkelmann's avatar
Michael Winkelmann committed
120
          paintItem(children, window, painter);
121
        }
Michael Winkelmann's avatar
Michael Winkelmann committed
122 123 124 125 126 127 128 129 130 131 132 133 134 135
      }
    }
  } 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
136
      QRectF rect(0,0,item->width(),item->height());
Michael Winkelmann's avatar
Michael Winkelmann committed
137
      if (window != nullptr) {
138
        QImage image = window->grabWindow();
139
        painter->drawImage(rect, image, rect);
Michael Winkelmann's avatar
Michael Winkelmann committed
140 141
      }
      drawChildren = false;
142
    }
Michael Winkelmann's avatar
Michael Winkelmann committed
143 144
  }
  if (drawChildren) {
145

Michael Winkelmann's avatar
Michael Winkelmann committed
146 147 148 149
    auto items = item->childItems();
    std::sort(items.begin(), items.end(), [](QQuickItem *lhs, QQuickItem *rhs) {
      return lhs->z() < rhs->z();
    });
150

Michael Winkelmann's avatar
Michael Winkelmann committed
151 152 153
    for (auto item : items)
      paintItem(item, window, painter);
  }
154

Michael Winkelmann's avatar
Michael Winkelmann committed
155
  painter->restore();
156 157
}

Michael Winkelmann's avatar
Michael Winkelmann committed
158 159 160 161 162
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;
163

Michael Winkelmann's avatar
Michael Winkelmann committed
164 165 166
  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());
167 168
}

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

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

Michael Winkelmann's avatar
Michael Winkelmann committed
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
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());
266
    }
Michael Winkelmann's avatar
Michael Winkelmann committed
267 268 269 270 271 272 273 274
    if (sourceRect.height() > rect.height()) {
      rect.setHeight(sourceRect.height());
    } else {
      sourceRect.setHeight(rect.height());
    }
  } break;
  }
  painter->drawImage(rect, image, sourceRect);
275 276
}

Michael Winkelmann's avatar
Michael Winkelmann committed
277 278 279 280 281 282 283
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;
284 285
}

Michael Winkelmann's avatar
Michael Winkelmann committed
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 311 312 313 314 315 316 317 318 319 320 321 322 323
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());
324
    }
Michael Winkelmann's avatar
Michael Winkelmann committed
325 326 327 328 329 330 331 332 333 334 335 336
    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();
337
}