qmlprinter.cpp 10.7 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
bool QmlPrinter::printPdf(const QString &location, QQuickItem *presentation) {
26 27 28 29
    if (!presentation) {
        return false;
    }

Michael Winkelmann's avatar
Michael Winkelmann committed
30 31 32 33
  QVector<QQuickItem *> slides, masterSlideElements;
  presentation->setProperty(
      "allowDelay",
      QVariant(false)); // Disable partial reveals on slide pages
34

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

Michael Winkelmann's avatar
Michael Winkelmann committed
44
  if (slides.length() == 0) {
45
      qCWarning(lc) << QObject::tr("No pages in %1, no PDF produced!").arg(location);
Michael Winkelmann's avatar
Michael Winkelmann committed
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
    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
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
124
        for (QQuickItem *children : listViewChildren) {
Michael Winkelmann's avatar
Michael Winkelmann committed
125
          paintItem(children, window, painter);
126
        }
Michael Winkelmann's avatar
Michael Winkelmann committed
127 128 129 130 131 132 133 134 135 136 137 138 139 140
      }
    }
  } 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
141
      QRectF rect(0,0,item->width(),item->height());
Michael Winkelmann's avatar
Michael Winkelmann committed
142
      if (window != nullptr) {
143
        QImage image = window->grabWindow();
144
        painter->drawImage(rect, image, rect);
Michael Winkelmann's avatar
Michael Winkelmann committed
145 146
      }
      drawChildren = false;
147
    }
Michael Winkelmann's avatar
Michael Winkelmann committed
148
  }
149

Michael Winkelmann's avatar
Michael Winkelmann committed
150
  if (drawChildren) {
151

Michael Winkelmann's avatar
Michael Winkelmann committed
152 153 154 155
    auto items = item->childItems();
    std::sort(items.begin(), items.end(), [](QQuickItem *lhs, QQuickItem *rhs) {
      return lhs->z() < rhs->z();
    });
156

Michael Winkelmann's avatar
Michael Winkelmann committed
157 158 159
    for (auto item : items)
      paintItem(item, window, painter);
  }
160

Michael Winkelmann's avatar
Michael Winkelmann committed
161
  painter->restore();
162 163
}

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

Michael Winkelmann's avatar
Michael Winkelmann committed
170 171 172
  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());
173 174
}

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

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

Michael Winkelmann's avatar
Michael Winkelmann committed
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
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());
272
    }
Michael Winkelmann's avatar
Michael Winkelmann committed
273 274 275 276 277 278 279 280
    if (sourceRect.height() > rect.height()) {
      rect.setHeight(sourceRect.height());
    } else {
      sourceRect.setHeight(rect.height());
    }
  } break;
  }
  painter->drawImage(rect, image, sourceRect);
281 282
}

Michael Winkelmann's avatar
Michael Winkelmann committed
283 284 285 286 287 288 289
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;
290 291
}

Michael Winkelmann's avatar
Michael Winkelmann committed
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 324 325 326 327 328 329
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());
330
    }
Michael Winkelmann's avatar
Michael Winkelmann committed
331 332 333 334 335 336 337 338 339 340 341 342
    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();
343
}