QGIS API Documentation 4.1.0-Master (26185ffb827)
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 // this needs to be done in main thread, layouts are not thread safe
126 QgsPrintLayout *l = parameterAsLayout( parameters, u"LAYOUT"_s, context );
127 if ( !l )
128 throw QgsProcessingException( QObject::tr( "Cannot find layout with name \"%1\"" ).arg( parameters.value( u"LAYOUT"_s ).toString() ) );
129
130 std::unique_ptr<QgsPrintLayout> layout( l->clone() );
131 QgsLayoutAtlas *atlas = layout->atlas();
132
133 QString expression, error;
134 QgsVectorLayer *layer = parameterAsVectorLayer( parameters, u"COVERAGE_LAYER"_s, context );
135 if ( layer )
136 {
137 atlas->setEnabled( true );
138 atlas->setCoverageLayer( layer );
139
140 expression = parameterAsString( parameters, u"FILTER_EXPRESSION"_s, context );
141 atlas->setFilterExpression( expression, error );
142 atlas->setFilterFeatures( !expression.isEmpty() && error.isEmpty() );
143 if ( !expression.isEmpty() && !error.isEmpty() )
144 {
145 throw QgsProcessingException( QObject::tr( "Error setting atlas filter expression" ) );
146 }
147 error.clear();
148
149 expression = parameterAsString( parameters, u"SORTBY_EXPRESSION"_s, context );
150 if ( !expression.isEmpty() )
151 {
152 const bool sortByReverse = parameterAsBool( parameters, u"SORTBY_REVERSE"_s, context );
153 atlas->setSortFeatures( true );
154 atlas->setSortExpression( expression );
155 atlas->setSortAscending( !sortByReverse );
156 }
157 else
158 {
159 atlas->setSortFeatures( false );
160 }
161 }
162 else if ( !atlas->enabled() )
163 {
164 throw QgsProcessingException( QObject::tr( "Layout being export doesn't have an enabled atlas" ) );
165 }
166
167 expression = parameterAsString( parameters, u"FILENAME_EXPRESSION"_s, context );
168 atlas->setFilenameExpression( expression, error );
169 if ( !error.isEmpty() )
170 {
171 throw QgsProcessingException( QObject::tr( "Error setting atlas filename expression" ) );
172 }
173
174 const QString directory = parameterAsFileOutput( parameters, u"FOLDER"_s, context );
175 const QString fileName = QDir( directory ).filePath( u"atlas"_s );
176
177 const QStringList imageFormats = QgsProcessingUtils::supportedImageFormats();
178 const int idx = parameterAsEnum( parameters, u"EXTENSION"_s, context );
179 const QString extension = '.' + imageFormats.at( idx ).toLower();
180
182
183 if ( parameters.value( u"DPI"_s ).isValid() )
184 {
185 settings.dpi = parameterAsDouble( parameters, u"DPI"_s, context );
186 }
187
188 settings.exportMetadata = parameterAsBool( parameters, u"INCLUDE_METADATA"_s, context );
189 settings.generateWorldFile = parameterAsBool( parameters, u"GEOREFERENCE"_s, context );
190
191 if ( parameterAsBool( parameters, u"ANTIALIAS"_s, context ) )
193 else
194 settings.flags = settings.flags & ~static_cast< int >( Qgis::LayoutRenderFlag::Antialiasing );
195
196 settings.predefinedMapScales = QgsLayoutUtils::predefinedScales( layout.get() );
197
198 const QList<QgsMapLayer *> layers = parameterAsLayerList( parameters, u"LAYERS"_s, context );
199 if ( layers.size() > 0 )
200 {
201 const QList<QGraphicsItem *> items = layout->items();
202 for ( QGraphicsItem *graphicsItem : items )
203 {
204 QgsLayoutItem *item = dynamic_cast<QgsLayoutItem *>( graphicsItem );
205 QgsLayoutItemMap *map = dynamic_cast<QgsLayoutItemMap *>( item );
206 if ( map && !map->followVisibilityPreset() && !map->keepLayerSet() )
207 {
208 map->setKeepLayerSet( true );
209 map->setLayers( layers );
210 }
211 }
212 }
213
214 if ( atlas->updateFeatures() )
215 {
216 feedback->pushInfo( QObject::tr( "Exporting %n atlas feature(s)", "", atlas->count() ) );
217 switch ( QgsLayoutExporter::exportToImage( atlas, fileName, extension, settings, error, feedback ) )
218 {
220 {
221 feedback->pushInfo( QObject::tr( "Successfully exported layout to %1" ).arg( QDir::toNativeSeparators( directory ) ) );
222 break;
223 }
224
226 throw QgsProcessingException( !error.isEmpty() ? error : QObject::tr( "Cannot write to %1.\n\nThis file may be open in another application." ).arg( QDir::toNativeSeparators( directory ) ) );
227
230 !error.isEmpty() ? error
231 : QObject::tr(
232 "Trying to create the image "
233 "resulted in a memory overflow.\n\n"
234 "Please try a lower resolution or a smaller paper size."
235 )
236 );
237
239 throw QgsProcessingException( !error.isEmpty() ? error : QObject::tr( "Error encountered while exporting atlas." ) );
240
244 // no meaning for imageexports, will not be encountered
245 break;
246 }
247 }
248 else
249 {
250 feedback->reportError( QObject::tr( "No atlas features found" ) );
251 }
252
253 feedback->setProgress( 100 );
254
255 QVariantMap outputs;
256 outputs.insert( u"FOLDER"_s, directory );
257 return outputs;
258}
259
@ MapLayer
Any map layer type (raster, vector, mesh, point cloud, annotation or plugin layer).
Definition qgis.h:3713
@ Folder
Parameter is a folder.
Definition qgis.h:3974
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3791
@ NoThreading
Algorithm is not thread safe and cannot be run in a background thread, e.g. for algorithms which mani...
Definition qgis.h:3770
@ RequiresProject
The algorithm requires that a valid QgsProject is available from the processing context in order to e...
Definition qgis.h:3778
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Definition qgis.h:3947
@ Double
Double/float values.
Definition qgis.h:3988
@ Antialiasing
Use antialiasing when drawing items.
Definition qgis.h:5643
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.
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.