qt - 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.
解决方案
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()
}
}
}
推荐阅读
- ios - CIContext createCGImage内存泄漏?
- powershell - 使用 powershell 在文件中搜索多行文本
- mysql - 如何使用 node.js、socket.io 和 mysql 显示实时数据?
- angular - 在嵌入的组件中使用父范围/方法/属性
- node.js - error..name :MongoNetworkError...message: '连接服务器失败
- bash - 使用 qsub 运行具有唯一名称的多个作业
- regex - 使用正则表达式解析自定义 URI
- scala - 是什么导致了scala中的类型转换
- arrays - 在 Python3 中加载 .mat 文件
- charts - Highcharts:如何在瀑布图中添加超过1个intermediateSum?