QGIS API Documentation 4.3.0-Master (d3b565c628d)
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 auto layersParam
88 = std::make_unique<QgsProcessingParameterMultipleLayers>( u"LAYERS"_s, QObject::tr( "Map layers to assign to unlocked map item(s)" ), Qgis::ProcessingSourceType::MapLayer, QVariant(), true );
89 layersParam->setFlags( layersParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
90 addParameter( layersParam.release() );
91
92 auto extensionParam = std::make_unique<QgsProcessingParameterEnum>( u"EXTENSION"_s, QObject::tr( "Image format" ), QgsProcessingUtils::supportedImageFormats(), false, 0 );
93 extensionParam->setFlags( extensionParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
94 addParameter( extensionParam.release() );
95
96 auto dpiParam = std::make_unique<QgsProcessingParameterNumber>( u"DPI"_s, QObject::tr( "DPI (leave blank for default layout DPI)" ), Qgis::ProcessingNumberParameterType::Double, QVariant(), true, 0 );
97 dpiParam->setFlags( dpiParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
98 addParameter( dpiParam.release() );
99
100 auto appendGeorefParam = std::make_unique<QgsProcessingParameterBoolean>( u"GEOREFERENCE"_s, QObject::tr( "Generate world file" ), true );
101 appendGeorefParam->setFlags( appendGeorefParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
102 addParameter( appendGeorefParam.release() );
103
104 auto exportRDFParam = std::make_unique<QgsProcessingParameterBoolean>( u"INCLUDE_METADATA"_s, QObject::tr( "Export RDF metadata (title, author, etc.)" ), true );
105 exportRDFParam->setFlags( exportRDFParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
106 addParameter( exportRDFParam.release() );
107
108 auto antialias = std::make_unique<QgsProcessingParameterBoolean>( u"ANTIALIAS"_s, QObject::tr( "Enable antialiasing" ), true );
109 antialias->setFlags( antialias->flags() | Qgis::ProcessingParameterFlag::Advanced );
110 addParameter( antialias.release() );
111}
112
113Qgis::ProcessingAlgorithmFlags QgsLayoutAtlasToImageAlgorithm::flags() const
114{
116}
117
118QgsLayoutAtlasToImageAlgorithm *QgsLayoutAtlasToImageAlgorithm::createInstance() const
119{
120 return new QgsLayoutAtlasToImageAlgorithm();
121}
122
123QVariantMap QgsLayoutAtlasToImageAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
124{
125 QGS_MARK_ALGORITHM_SOURCE
126
127 // this needs to be done in main thread, layouts are not thread safe
128 QgsPrintLayout *l = parameterAsLayout( parameters, u"LAYOUT"_s, context );
129 if ( !l )
130 throw QgsProcessingException( QObject::tr( "Cannot find layout with name \"%1\"" ).arg( parameters.value( u"LAYOUT"_s ).toString() ) );
131
132 std::unique_ptr<QgsPrintLayout> layout( l->clone() );
133 QgsLayoutAtlas *atlas = layout->atlas();
134
135 QString expression, error;
136 QgsVectorLayer *layer = parameterAsVectorLayer( parameters, u"COVERAGE_LAYER"_s, context );
137 if ( layer )
138 {
139 atlas->setEnabled( true );
140 atlas->setCoverageLayer( layer );
141
142 expression = parameterAsString( parameters, u"FILTER_EXPRESSION"_s, context );
143 atlas->setFilterExpression( expression, error );
144 atlas->setFilterFeatures( !expression.isEmpty() && error.isEmpty() );
145 if ( !expression.isEmpty() && !error.isEmpty() )
146 {
147 throw QgsProcessingException( QObject::tr( "Error setting atlas filter expression" ) );
148 }
149 error.clear();
150
151 expression = parameterAsString( parameters, u"SORTBY_EXPRESSION"_s, context );
152 if ( !expression.isEmpty() )
153 {
154 const bool sortByReverse = parameterAsBool( parameters, u"SORTBY_REVERSE"_s, context );
155 atlas->setSortFeatures( true );
156 atlas->setSortExpression( expression );
157 atlas->setSortAscending( !sortByReverse );
158 }
159 else
160 {
161 atlas->setSortFeatures( false );
162 }
163 }
164 else if ( !atlas->enabled() )
165 {
166 throw QgsProcessingException( QObject::tr( "Layout being export doesn't have an enabled atlas" ) );
167 }
168
169 expression = parameterAsString( parameters, u"FILENAME_EXPRESSION"_s, context );
170 atlas->setFilenameExpression( expression, error );
171 if ( !error.isEmpty() )
172 {
173 throw QgsProcessingException( QObject::tr( "Error setting atlas filename expression" ) );
174 }
175
176 const QString directory = parameterAsFileOutput( parameters, u"FOLDER"_s, context );
177 const QString fileName = QDir( directory ).filePath( u"atlas"_s );
178
179 const QStringList imageFormats = QgsProcessingUtils::supportedImageFormats();
180 const int idx = parameterAsEnum( parameters, u"EXTENSION"_s, context );
181 const QString extension = '.' + imageFormats.at( idx ).toLower();
182
184
185 if ( parameters.value( u"DPI"_s ).isValid() )
186 {
187 settings.dpi = parameterAsDouble( parameters, u"DPI"_s, context );
188 }
189
190 settings.exportMetadata = parameterAsBool( parameters, u"INCLUDE_METADATA"_s, context );
191 settings.generateWorldFile = parameterAsBool( parameters, u"GEOREFERENCE"_s, context );
192
193 if ( parameterAsBool( parameters, u"ANTIALIAS"_s, context ) )
195 else
196 settings.flags = settings.flags & ~static_cast< int >( Qgis::LayoutRenderFlag::Antialiasing );
197
198 settings.predefinedMapScales = QgsLayoutUtils::predefinedScales( layout.get() );
199
200 const QList<QgsMapLayer *> layers = parameterAsLayerList( parameters, u"LAYERS"_s, context );
201 if ( layers.size() > 0 )
202 {
203 const QList<QGraphicsItem *> items = layout->items();
204 for ( QGraphicsItem *graphicsItem : items )
205 {
206 QgsLayoutItem *item = dynamic_cast<QgsLayoutItem *>( graphicsItem );
207 QgsLayoutItemMap *map = dynamic_cast<QgsLayoutItemMap *>( item );
208 if ( map && !map->followVisibilityPreset() && !map->keepLayerSet() )
209 {
210 map->setKeepLayerSet( true );
211 map->setLayers( layers );
212 }
213 }
214 }
215
216 if ( atlas->updateFeatures() )
217 {
218 feedback->pushInfo( QObject::tr( "Exporting %n atlas feature(s)", "", atlas->count() ) );
219 switch ( QgsLayoutExporter::exportToImage( atlas, fileName, extension, settings, error, feedback ) )
220 {
222 {
223 feedback->pushInfo( QObject::tr( "Successfully exported layout to %1" ).arg( QDir::toNativeSeparators( directory ) ) );
224 break;
225 }
226
228 throw QgsProcessingException( !error.isEmpty() ? error : QObject::tr( "Cannot write to %1.\n\nThis file may be open in another application." ).arg( QDir::toNativeSeparators( directory ) ) );
229
232 !error.isEmpty() ? error
233 : QObject::tr(
234 "Trying to create the image "
235 "resulted in a memory overflow.\n\n"
236 "Please try a lower resolution or a smaller paper size."
237 )
238 );
239
241 throw QgsProcessingException( !error.isEmpty() ? error : QObject::tr( "Error encountered while exporting atlas." ) );
242
246 // no meaning for imageexports, will not be encountered
247 break;
248 }
249 }
250 else
251 {
252 feedback->reportError( QObject::tr( "No atlas features found" ) );
253 }
254
255 feedback->setProgress( 100 );
256
257 QVariantMap outputs;
258 outputs.insert( u"FOLDER"_s, directory );
259 return outputs;
260}
261
@ MapLayer
Any map layer type (raster, vector, mesh, point cloud, annotation or plugin layer).
Definition qgis.h:3748
@ Folder
Parameter is a folder.
Definition qgis.h:4009
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3826
@ NoThreading
Algorithm is not thread safe and cannot be run in a background thread, e.g. for algorithms which mani...
Definition qgis.h:3805
@ RequiresProject
The algorithm requires that a valid QgsProject is available from the processing context in order to e...
Definition qgis.h:3813
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Definition qgis.h:3982
@ Double
Double/float values.
Definition qgis.h:4023
@ Antialiasing
Use antialiasing when drawing items.
Definition qgis.h:5739
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.
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.
static QStringList supportedImageFormats()
Returns a list of image format extensions supported by QImageWriter.
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.