QGIS API Documentation 4.1.0-Master (5bf3c20f3c9)
Loading...
Searching...
No Matches
qgsalgorithmlayoutatlastoimage.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmlayoutatlastoimage.cpp
3 ---------------------
4 begin : June 2020
5 copyright : (C) 2020 by Mathieu Pellerin
6 email : nirvn dot asia 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 "qgslayoutatlas.h"
22#include "qgslayoutexporter.h"
23#include "qgslayoutitemmap.h"
24#include "qgslayoututils.h"
25#include "qgsprintlayout.h"
27
28#include <QImageWriter>
29#include <QString>
30
31using namespace Qt::StringLiterals;
32
34
35QString QgsLayoutAtlasToImageAlgorithm::name() const
36{
37 return u"atlaslayouttoimage"_s;
38}
39
40QString QgsLayoutAtlasToImageAlgorithm::displayName() const
41{
42 return QObject::tr( "Export atlas layout as image" );
43}
44
45QStringList QgsLayoutAtlasToImageAlgorithm::tags() const
46{
47 return QObject::tr( "layout,atlas,composer,composition,save,png,jpeg,jpg" ).split( ',' );
48}
49
50QString QgsLayoutAtlasToImageAlgorithm::group() const
51{
52 return QObject::tr( "Cartography" );
53}
54
55QString QgsLayoutAtlasToImageAlgorithm::groupId() const
56{
57 return u"cartography"_s;
58}
59
60QString QgsLayoutAtlasToImageAlgorithm::shortDescription() const
61{
62 return QObject::tr( "Exports an atlas layout as a set of images." );
63}
64
65QString QgsLayoutAtlasToImageAlgorithm::shortHelpString() const
66{
67 return QObject::tr(
68 "This algorithm outputs an atlas layout to a set of image files (e.g. PNG or JPEG images).\n\n"
69 "If a coverage layer is set, the selected layout's atlas settings exposed in this algorithm "
70 "will be overwritten. In this case, an empty filter or sort by expression will turn those "
71 "settings off."
72 );
73}
74
75void QgsLayoutAtlasToImageAlgorithm::initAlgorithm( const QVariantMap & )
76{
77 addParameter( new QgsProcessingParameterLayout( u"LAYOUT"_s, QObject::tr( "Atlas layout" ) ) );
78
79 addParameter( new QgsProcessingParameterVectorLayer( u"COVERAGE_LAYER"_s, QObject::tr( "Coverage layer" ), QList<int>(), QVariant(), true ) );
80 addParameter( new QgsProcessingParameterExpression( u"FILTER_EXPRESSION"_s, QObject::tr( "Filter expression" ), QString(), u"COVERAGE_LAYER"_s, true ) );
81 addParameter( new QgsProcessingParameterExpression( u"SORTBY_EXPRESSION"_s, QObject::tr( "Sort expression" ), QString(), u"COVERAGE_LAYER"_s, true ) );
82 addParameter( new QgsProcessingParameterBoolean( u"SORTBY_REVERSE"_s, QObject::tr( "Reverse sort order (used when a sort expression is provided)" ), false ) );
83
84 addParameter( new QgsProcessingParameterExpression( u"FILENAME_EXPRESSION"_s, QObject::tr( "Output filename expression" ), u"'output_'||@atlas_featurenumber"_s, u"COVERAGE_LAYER"_s ) );
85 addParameter( new QgsProcessingParameterFile( u"FOLDER"_s, QObject::tr( "Output folder" ), Qgis::ProcessingFileParameterBehavior::Folder ) );
86
87
88 auto layersParam
89 = std::make_unique<QgsProcessingParameterMultipleLayers>( u"LAYERS"_s, QObject::tr( "Map layers to assign to unlocked map item(s)" ), Qgis::ProcessingSourceType::MapLayer, QVariant(), true );
90 layersParam->setFlags( layersParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
91 addParameter( layersParam.release() );
92
93 QStringList imageFormats;
94 const QList<QByteArray> supportedImageFormats { QImageWriter::supportedImageFormats() };
95 for ( const QByteArray &format : supportedImageFormats )
96 {
97 if ( format == QByteArray( "svg" ) )
98 continue;
99 imageFormats << QString( format );
100 }
101 auto extensionParam = std::make_unique<QgsProcessingParameterEnum>( u"EXTENSION"_s, QObject::tr( "Image format" ), imageFormats, false, imageFormats.indexOf( "png"_L1 ) );
102 extensionParam->setFlags( extensionParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
103 addParameter( extensionParam.release() );
104
105 auto dpiParam = std::make_unique<QgsProcessingParameterNumber>( u"DPI"_s, QObject::tr( "DPI (leave blank for default layout DPI)" ), Qgis::ProcessingNumberParameterType::Double, QVariant(), true, 0 );
106 dpiParam->setFlags( dpiParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
107 addParameter( dpiParam.release() );
108
109 auto appendGeorefParam = std::make_unique<QgsProcessingParameterBoolean>( u"GEOREFERENCE"_s, QObject::tr( "Generate world file" ), true );
110 appendGeorefParam->setFlags( appendGeorefParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
111 addParameter( appendGeorefParam.release() );
112
113 auto exportRDFParam = std::make_unique<QgsProcessingParameterBoolean>( u"INCLUDE_METADATA"_s, QObject::tr( "Export RDF metadata (title, author, etc.)" ), true );
114 exportRDFParam->setFlags( exportRDFParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
115 addParameter( exportRDFParam.release() );
116
117 auto antialias = std::make_unique<QgsProcessingParameterBoolean>( u"ANTIALIAS"_s, QObject::tr( "Enable antialiasing" ), true );
118 antialias->setFlags( antialias->flags() | Qgis::ProcessingParameterFlag::Advanced );
119 addParameter( antialias.release() );
120}
121
122Qgis::ProcessingAlgorithmFlags QgsLayoutAtlasToImageAlgorithm::flags() const
123{
125}
126
127QgsLayoutAtlasToImageAlgorithm *QgsLayoutAtlasToImageAlgorithm::createInstance() const
128{
129 return new QgsLayoutAtlasToImageAlgorithm();
130}
131
132QVariantMap QgsLayoutAtlasToImageAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
133{
134 // this needs to be done in main thread, layouts are not thread safe
135 QgsPrintLayout *l = parameterAsLayout( parameters, u"LAYOUT"_s, context );
136 if ( !l )
137 throw QgsProcessingException( QObject::tr( "Cannot find layout with name \"%1\"" ).arg( parameters.value( u"LAYOUT"_s ).toString() ) );
138
139 std::unique_ptr<QgsPrintLayout> layout( l->clone() );
140 QgsLayoutAtlas *atlas = layout->atlas();
141
142 QString expression, error;
143 QgsVectorLayer *layer = parameterAsVectorLayer( parameters, u"COVERAGE_LAYER"_s, context );
144 if ( layer )
145 {
146 atlas->setEnabled( true );
147 atlas->setCoverageLayer( layer );
148
149 expression = parameterAsString( parameters, u"FILTER_EXPRESSION"_s, context );
150 atlas->setFilterExpression( expression, error );
151 atlas->setFilterFeatures( !expression.isEmpty() && error.isEmpty() );
152 if ( !expression.isEmpty() && !error.isEmpty() )
153 {
154 throw QgsProcessingException( QObject::tr( "Error setting atlas filter expression" ) );
155 }
156 error.clear();
157
158 expression = parameterAsString( parameters, u"SORTBY_EXPRESSION"_s, context );
159 if ( !expression.isEmpty() )
160 {
161 const bool sortByReverse = parameterAsBool( parameters, u"SORTBY_REVERSE"_s, context );
162 atlas->setSortFeatures( true );
163 atlas->setSortExpression( expression );
164 atlas->setSortAscending( !sortByReverse );
165 }
166 else
167 {
168 atlas->setSortFeatures( false );
169 }
170 }
171 else if ( !atlas->enabled() )
172 {
173 throw QgsProcessingException( QObject::tr( "Layout being export doesn't have an enabled atlas" ) );
174 }
175
176 expression = parameterAsString( parameters, u"FILENAME_EXPRESSION"_s, context );
177 atlas->setFilenameExpression( expression, error );
178 if ( !error.isEmpty() )
179 {
180 throw QgsProcessingException( QObject::tr( "Error setting atlas filename expression" ) );
181 }
182
183 const QString directory = parameterAsFileOutput( parameters, u"FOLDER"_s, context );
184 const QString fileName = QDir( directory ).filePath( u"atlas"_s );
185
186 QStringList imageFormats;
187 const QList<QByteArray> supportedImageFormats { QImageWriter::supportedImageFormats() };
188 for ( const QByteArray &format : supportedImageFormats )
189 {
190 if ( format == QByteArray( "svg" ) )
191 continue;
192 imageFormats << QString( format );
193 }
194 const int idx = parameterAsEnum( parameters, u"EXTENSION"_s, context );
195 const QString extension = '.' + imageFormats.at( idx );
196
198
199 if ( parameters.value( u"DPI"_s ).isValid() )
200 {
201 settings.dpi = parameterAsDouble( parameters, u"DPI"_s, context );
202 }
203
204 settings.exportMetadata = parameterAsBool( parameters, u"INCLUDE_METADATA"_s, context );
205 settings.generateWorldFile = parameterAsBool( parameters, u"GEOREFERENCE"_s, context );
206
207 if ( parameterAsBool( parameters, u"ANTIALIAS"_s, context ) )
209 else
210 settings.flags = settings.flags & ~static_cast< int >( Qgis::LayoutRenderFlag::Antialiasing );
211
212 settings.predefinedMapScales = QgsLayoutUtils::predefinedScales( layout.get() );
213
214 const QList<QgsMapLayer *> layers = parameterAsLayerList( parameters, u"LAYERS"_s, context );
215 if ( layers.size() > 0 )
216 {
217 const QList<QGraphicsItem *> items = layout->items();
218 for ( QGraphicsItem *graphicsItem : items )
219 {
220 QgsLayoutItem *item = dynamic_cast<QgsLayoutItem *>( graphicsItem );
221 QgsLayoutItemMap *map = dynamic_cast<QgsLayoutItemMap *>( item );
222 if ( map && !map->followVisibilityPreset() && !map->keepLayerSet() )
223 {
224 map->setKeepLayerSet( true );
225 map->setLayers( layers );
226 }
227 }
228 }
229
230 if ( atlas->updateFeatures() )
231 {
232 feedback->pushInfo( QObject::tr( "Exporting %n atlas feature(s)", "", atlas->count() ) );
233 switch ( QgsLayoutExporter::exportToImage( atlas, fileName, extension, settings, error, feedback ) )
234 {
236 {
237 feedback->pushInfo( QObject::tr( "Successfully exported layout to %1" ).arg( QDir::toNativeSeparators( directory ) ) );
238 break;
239 }
240
242 throw QgsProcessingException( !error.isEmpty() ? error : QObject::tr( "Cannot write to %1.\n\nThis file may be open in another application." ).arg( QDir::toNativeSeparators( directory ) ) );
243
246 !error.isEmpty() ? error
247 : QObject::tr(
248 "Trying to create the image "
249 "resulted in a memory overflow.\n\n"
250 "Please try a lower resolution or a smaller paper size."
251 )
252 );
253
255 throw QgsProcessingException( !error.isEmpty() ? error : QObject::tr( "Error encountered while exporting atlas." ) );
256
260 // no meaning for imageexports, will not be encountered
261 break;
262 }
263 }
264 else
265 {
266 feedback->reportError( QObject::tr( "No atlas features found" ) );
267 }
268
269 feedback->setProgress( 100 );
270
271 QVariantMap outputs;
272 outputs.insert( u"FOLDER"_s, directory );
273 return outputs;
274}
275
@ MapLayer
Any map layer type (raster, vector, mesh, point cloud, annotation or plugin layer).
Definition qgis.h:3646
@ Folder
Parameter is a folder.
Definition qgis.h:3907
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
Used to render QgsLayout as an atlas, by iterating over the features from an associated vector layer.
void setCoverageLayer(QgsVectorLayer *layer)
Sets the coverage layer to use for the atlas features.
bool setFilterExpression(const QString &expression, QString &errorString)
Sets the expression used for filtering features in the coverage layer.
void setSortAscending(bool ascending)
Sets whether features should be sorted in an ascending order.
void setEnabled(bool enabled)
Sets whether the atlas is enabled.
bool enabled() const
Returns whether the atlas generation is enabled.
bool setFilenameExpression(const QString &expression, QString &errorString)
Sets the filename expression used for generating output filenames for each atlas page.
void setSortFeatures(bool enabled)
Sets whether features should be sorted in the atlas.
int count() const override
Returns the number of features to iterate over.
void setSortExpression(const QString &expression)
Sets the expression (or field name) to use for sorting features.
void setFilterFeatures(bool filtered)
Sets whether features should be filtered in the coverage layer.
int updateFeatures()
Requeries the current atlas coverage layer and applies filtering and sorting.
ExportResult exportToImage(const QString &filePath, const QgsLayoutExporter::ImageExportSettings &settings)
Exports the layout to the filePath, using the specified export settings.
@ 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.
static QVector< double > predefinedScales(const QgsLayout *layout)
Returns a list of predefined scales associated with a layout.
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.
virtual void reportError(const QString &error, bool fatalError=false)
Reports that the algorithm encountered an error while executing.
A boolean parameter for processing algorithms.
An expression parameter for processing algorithms.
An input file or folder parameter for processing algorithms.
A print layout parameter, allowing users to select a print layout.
A vector layer (with or without geometry) parameter for processing algorithms.
Represents a vector layer which manages a vector based dataset.
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.
QVector< qreal > predefinedMapScales
A list of predefined scales to use with the layout.