QGIS API Documentation 4.1.0-Master (5bf3c20f3c9)
Loading...
Searching...
No Matches
qgsalgorithmlayouttoimage.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmlayouttoimage.cpp
3 ---------------------
4 begin : June 2020
5 copyright : (C) 2020 by Nyall Dawson
6 email : nyall dot dawson at gmail dot com
7 ***************************************************************************/
8
9/***************************************************************************
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 ***************************************************************************/
17
19
20#include "qgslayout.h"
21#include "qgslayoutexporter.h"
22#include "qgslayoutitemmap.h"
23#include "qgsprintlayout.h"
25
26#include <QImageWriter>
27#include <QString>
28
29using namespace Qt::StringLiterals;
30
32
33QString QgsLayoutToImageAlgorithm::name() const
34{
35 return u"printlayouttoimage"_s;
36}
37
38QString QgsLayoutToImageAlgorithm::displayName() const
39{
40 return QObject::tr( "Export print layout as image" );
41}
42
43QStringList QgsLayoutToImageAlgorithm::tags() const
44{
45 return QObject::tr( "layout,composer,composition,save,png,jpeg,jpg" ).split( ',' );
46}
47
48QString QgsLayoutToImageAlgorithm::group() const
49{
50 return QObject::tr( "Cartography" );
51}
52
53QString QgsLayoutToImageAlgorithm::groupId() const
54{
55 return u"cartography"_s;
56}
57
58QString QgsLayoutToImageAlgorithm::shortDescription() const
59{
60 return QObject::tr( "Exports a print layout as an image." );
61}
62
63QString QgsLayoutToImageAlgorithm::shortHelpString() const
64{
65 return QObject::tr( "This algorithm outputs a print layout as an image file (e.g. PNG or JPEG images)." );
66}
67
68void QgsLayoutToImageAlgorithm::initAlgorithm( const QVariantMap & )
69{
70 addParameter( new QgsProcessingParameterLayout( u"LAYOUT"_s, QObject::tr( "Print layout" ) ) );
71
72 auto layersParam
73 = std::make_unique<QgsProcessingParameterMultipleLayers>( u"LAYERS"_s, QObject::tr( "Map layers to assign to unlocked map item(s)" ), Qgis::ProcessingSourceType::MapLayer, QVariant(), true );
74 layersParam->setFlags( layersParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
75 addParameter( layersParam.release() );
76
77 auto dpiParam = std::make_unique<QgsProcessingParameterNumber>( u"DPI"_s, QObject::tr( "DPI (leave blank for default layout DPI)" ), Qgis::ProcessingNumberParameterType::Double, QVariant(), true, 0 );
78 dpiParam->setFlags( dpiParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
79 addParameter( dpiParam.release() );
80
81 auto appendGeorefParam = std::make_unique<QgsProcessingParameterBoolean>( u"GEOREFERENCE"_s, QObject::tr( "Generate world file" ), true );
82 appendGeorefParam->setFlags( appendGeorefParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
83 addParameter( appendGeorefParam.release() );
84
85 auto exportRDFParam = std::make_unique<QgsProcessingParameterBoolean>( u"INCLUDE_METADATA"_s, QObject::tr( "Export RDF metadata (title, author, etc.)" ), true );
86 exportRDFParam->setFlags( exportRDFParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
87 addParameter( exportRDFParam.release() );
88
89 auto antialias = std::make_unique<QgsProcessingParameterBoolean>( u"ANTIALIAS"_s, QObject::tr( "Enable antialiasing" ), true );
90 antialias->setFlags( antialias->flags() | Qgis::ProcessingParameterFlag::Advanced );
91 addParameter( antialias.release() );
92
93 QStringList imageFilters;
94 const auto supportedImageFormats { QImageWriter::supportedImageFormats() };
95 for ( const QByteArray &format : supportedImageFormats )
96 {
97 if ( format == "svg" )
98 continue;
99
100 const QString longName = format.toUpper() + QObject::tr( " format" );
101 const QString glob = u"*."_s + format;
102
103 if ( format == "png" && !imageFilters.empty() )
104 imageFilters.insert( 0, u"%1 (%2 %3)"_s.arg( longName, glob.toLower(), glob.toUpper() ) );
105 else
106 imageFilters.append( u"%1 (%2 %3)"_s.arg( longName, glob.toLower(), glob.toUpper() ) );
107 }
108
109 addParameter( new QgsProcessingParameterFileDestination( u"OUTPUT"_s, QObject::tr( "Image file" ), imageFilters.join( ";;"_L1 ) ) );
110}
111
112Qgis::ProcessingAlgorithmFlags QgsLayoutToImageAlgorithm::flags() const
113{
115}
116
117QgsLayoutToImageAlgorithm *QgsLayoutToImageAlgorithm::createInstance() const
118{
119 return new QgsLayoutToImageAlgorithm();
120}
121
122QVariantMap QgsLayoutToImageAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
123{
124 // this needs to be done in main thread, layouts are not thread safe
125 QgsPrintLayout *l = parameterAsLayout( parameters, u"LAYOUT"_s, context );
126 if ( !l )
127 throw QgsProcessingException( QObject::tr( "Cannot find layout with name \"%1\"" ).arg( parameters.value( u"LAYOUT"_s ).toString() ) );
128 std::unique_ptr<QgsPrintLayout> layout( l->clone() );
129
130 const QList<QgsMapLayer *> layers = parameterAsLayerList( parameters, u"LAYERS"_s, context );
131 if ( layers.size() > 0 )
132 {
133 const QList<QGraphicsItem *> items = layout->items();
134 for ( QGraphicsItem *graphicsItem : items )
135 {
136 QgsLayoutItem *item = dynamic_cast<QgsLayoutItem *>( graphicsItem );
137 QgsLayoutItemMap *map = dynamic_cast<QgsLayoutItemMap *>( item );
138 if ( map && !map->followVisibilityPreset() && !map->keepLayerSet() )
139 {
140 map->setKeepLayerSet( true );
141 map->setLayers( layers );
142 }
143 }
144 }
145
146 const QString dest = parameterAsFileOutput( parameters, u"OUTPUT"_s, context );
147
148 QgsLayoutExporter exporter( layout.get() );
150
151 if ( parameters.value( u"DPI"_s ).isValid() )
152 {
153 settings.dpi = parameterAsDouble( parameters, u"DPI"_s, context );
154 }
155
156 settings.exportMetadata = parameterAsBool( parameters, u"INCLUDE_METADATA"_s, context );
157 settings.generateWorldFile = parameterAsBool( parameters, u"GEOREFERENCE"_s, context );
158
159 if ( parameterAsBool( parameters, u"ANTIALIAS"_s, context ) )
161 else
162 settings.flags = settings.flags & ~static_cast< int >( Qgis::LayoutRenderFlag::Antialiasing );
163
164 switch ( exporter.exportToImage( dest, settings ) )
165 {
167 {
168 feedback->pushInfo( QObject::tr( "Successfully exported layout to %1" ).arg( QDir::toNativeSeparators( dest ) ) );
169 break;
170 }
171
174 !exporter.errorMessage().isEmpty() ? exporter.errorMessage() : QObject::tr( "Cannot write to %1.\n\nThis file may be open in another application." ).arg( QDir::toNativeSeparators( dest ) )
175 );
176
179 !exporter.errorMessage().isEmpty() ? exporter.errorMessage()
180 : QObject::tr(
181 "Trying to create the image "
182 "resulted in a memory overflow.\n\n"
183 "Please try a lower resolution or a smaller paper size."
184 )
185 );
186
191 // no meaning for imageexports, will not be encountered
192 break;
193 }
194
195 feedback->setProgress( 100 );
196
197 QVariantMap outputs;
198 outputs.insert( u"OUTPUT"_s, dest );
199 return outputs;
200}
201
@ MapLayer
Any map layer type (raster, vector, mesh, point cloud, annotation or plugin layer).
Definition qgis.h:3646
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3724
@ NoThreading
Algorithm is not thread safe and cannot be run in a background thread, e.g. for algorithms which mani...
Definition qgis.h:3703
@ RequiresProject
The algorithm requires that a valid QgsProject is available from the processing context in order to e...
Definition qgis.h:3711
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Definition qgis.h:3880
@ Double
Double/float values.
Definition qgis.h:3921
@ Antialiasing
Use antialiasing when drawing items.
Definition qgis.h:5397
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:65
Handles rendering and exports of layouts to various formats.
@ Canceled
Export was canceled.
@ MemoryError
Unable to allocate memory required to export.
@ PrintError
Could not start printing to destination device.
@ IteratorError
Error iterating over layout.
@ FileError
Could not write to destination file, likely due to a lock held by another application.
@ Success
Export was successful.
@ SvgLayerError
Could not create layered SVG file.
Layout graphical items for displaying a map.
bool keepLayerSet() const
Returns whether a stored layer set should be used or the current layer set from the project associate...
void setKeepLayerSet(bool enabled)
Sets whether the stored layer set should be used or the current layer set of the associated project.
bool followVisibilityPreset() const
Returns whether the map should follow a map theme.
void setLayers(const QList< QgsMapLayer * > &layers)
Sets the stored layers set.
Base class for graphical items within a QgsLayout.
Print layout, a QgsLayout subclass for static or atlas-based layouts.
QgsPrintLayout * clone() const override
Creates a clone of the layout.
virtual Qgis::ProcessingAlgorithmFlags flags() const
Returns the flags indicating how and when the algorithm operates and should be exposed to users.
Contains information about the context in which a processing algorithm is executed.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
virtual void pushInfo(const QString &info)
Pushes a general informational message from the algorithm.
A generic file based destination parameter, for specifying the destination path for a file (non-map l...
A print layout parameter, allowing users to select a print layout.
Contains settings relating to exporting layouts to raster images.
bool generateWorldFile
Set to true to generate an external world file alongside exported images.
bool exportMetadata
Indicates whether image export should include metadata generated from the layout's project's metadata...
Qgis::LayoutRenderFlags flags
Layout context flags, which control how the export will be created.
double dpi
Resolution to export layout at. If dpi <= 0 the default layout dpi will be used.