首页 > 解决方案 > Export as PDF UI Scene(QML)

问题描述

I want the images and texts appearing in the interface to be rendered as PDF. I have a button and when the button is triggered, it saves whatever is on the screen that appears in the interface as a PDF(like export as PDF) . For this, I looked at the resources and the topics opened in the forum, but I could not reach a clear result. I would be very happy if you could help with this.

标签: qtqml

解决方案


You should enable PrintSupport module in your .pro file like QT+=PrintSupport

First declare Drawer class like this :

#pragma once
#include <QQmlApplicationEngine>

class PdfExporter : public QQmlApplicationEngine
{
    Q_OBJECT

public:
    PdfExporter(QQmlApplicationEngine * engine);
    Q_INVOKABLE void screenShot();
private:
    QQmlApplicationEngine * mEngine;
};

and define:

#include <Drawer.h>
#include <QQuickWindow>
#include <QPrinter>
#include <QPainter>

PdfExporter::PdfExporter(QQmlApplicationEngine *engine) : QQmlApplicationEngine(engine), mEngine(engine)
{

}

void PdfExporter::screenShot()
{
    foreach(QObject* obj, mEngine->rootObjects()) {
      QQuickWindow* window = qobject_cast<QQuickWindow*>(obj);
      if (window)
      {
        QImage windowImage = window->grabWindow();
        QPrinter pdfPrinter(QPrinter::HighResolution);
        pdfPrinter.setOutputFormat(QPrinter::PdfFormat);
        pdfPrinter.setOutputFileName("test.pdf");
        QPainter painter;
        painter.begin(&pdfPrinter);
        painter.drawImage(QRect(0,0,windowImage.width(),windowImage.height()),windowImage,{0,0,windowImage.width(),windowImage.height()});
        painter.end();
      }
    }
}

In the main.cpp I preferred to export C++ class as context property to engine.

 PdfExporter * dr = new PdfExporter(&engine);
 engine.rootContext()->setContextProperty("drawer",dr);

In QML you can trigger function like :

import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.12
import QtQuick.Layouts 1.12

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    ColumnLayout
    {
        anchors.centerIn: parent
        Rectangle
        {
            Layout.preferredWidth:  200
            Layout.preferredHeight:  100
            color: "red"
        }

        Button
        {
            Layout.preferredWidth:  100
            Layout.preferredHeight:  20
            Layout.alignment: Qt.AlignHCenter
            text: "test"
            onClicked: drawer.screenShot()
        }
    }
}

推荐阅读