| 1 | /* |
| 2 | * Copyright (C) 2018 Damir Porobic <[email protected]> |
| 3 | * |
| 4 | * This program is free software; you can redistribute it and/or modify |
| 5 | * it under the terms of the GNU General Public License as published by |
| 6 | * the Free Software Foundation; either version 2 of the License, or |
| 7 | * (at your option) any later version. |
| 8 | * |
| 9 | * This program is distributed in the hope that it will be useful, |
| 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | * GNU General Public License for more details. |
| 13 | * |
| 14 | * You should have received a copy of the GNU General Public License |
| 15 | * along with this program; if not, write to the Free Software |
| 16 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, |
| 17 | * Boston, MA 02110-1301, USA. |
| 18 | */ |
| 19 | |
| 20 | #include "CapturePrinter.h" |
| 21 | |
| 22 | CapturePrinter::CapturePrinter(QWidget *parent) : mParent(parent) |
| 23 | { |
| 24 | Q_ASSERT(mParent != nullptr); |
| 25 | } |
| 26 | |
| 27 | void CapturePrinter::print(const QImage &image, const QString &defaultPath) |
| 28 | { |
| 29 | QPrinter printer; |
| 30 | printer.setOutputFileName(defaultPath); |
| 31 | printer.setOutputFormat(QPrinter::NativeFormat); |
| 32 | QPrintDialog printDialog(&printer, mParent); |
| 33 | |
| 34 | if (printDialog.exec() == QDialog::Accepted) { |
| 35 | printCapture(image, &printer); |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | void CapturePrinter::printCapture(const QImage &image, QPrinter *p) |
| 40 | { |
| 41 | QPainter painter; |
| 42 | painter.begin(p); |
| 43 | auto rect = p->pageLayout().paintRectPixels(p->resolution()); |
| 44 | auto paperRect = p->pageLayout().fullRectPixels(p->resolution()); |
| 45 | auto xScale = rect.width() / double(image.width()); |
| 46 | auto yScale = rect.height() / double(image.height()); |
| 47 | auto scale = qMin(xScale, yScale); |
| 48 | painter.translate(paperRect.x() + rect.width() / 2, |
| 49 | paperRect.y() + rect.height() / 2); |
| 50 | painter.scale(scale, scale); |
| 51 | painter.translate(-image.width() / 2, -image.height() / 2); |
| 52 | painter.drawImage(QPoint(0, 0), image); |
| 53 | painter.end(); |
| 54 | } |
| 55 | |
| 56 | void CapturePrinter::printPreview(const QImage &image, const QString &defaultPath) |
| 57 | { |
| 58 | QPrinter printer; |
| 59 | printer.setOutputFileName(defaultPath); |
| 60 | printer.setOutputFormat(QPrinter::NativeFormat); |
| 61 | QPrintPreviewDialog printDialog(&printer, mParent, Qt::Window | Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::WindowMaximizeButtonHint | Qt::WindowCloseButtonHint); |
| 62 | connect(&printDialog, &QPrintPreviewDialog::paintRequested, [this, image](QPrinter *p) |
| 63 | { |
| 64 | printCapture(image, p); |
| 65 | }); |
| 66 | printDialog.exec(); |
| 67 | } |