QGIS API Documentation 3.99.0-Master (26c88405ac0)
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
31
32QString QgsLayoutAtlasToImageAlgorithm::name() const
33{
34 return QStringLiteral( "atlaslayouttoimage" );
35}
36
37QString QgsLayoutAtlasToImageAlgorithm::displayName() const
38{
39 return QObject::tr( "Export atlas layout as image" );
40}
41
42QStringList QgsLayoutAtlasToImageAlgorithm::tags() const
43{
44 return QObject::tr( "layout,atlas,composer,composition,save,png,jpeg,jpg" ).split( ',' );
45}
46
47QString QgsLayoutAtlasToImageAlgorithm::group() const
48{
49 return QObject::tr( "Cartography" );
50}
51
52QString QgsLayoutAtlasToImageAlgorithm::groupId() const
53{
54 return QStringLiteral( "cartography" );
55}
56
57QString QgsLayoutAtlasToImageAlgorithm::shortDescription() const
58{
59 return QObject::tr( "Exports an atlas layout as a set of images." );
60}
61
62QString QgsLayoutAtlasToImageAlgorithm::shortHelpString() const
63{
64 return QObject::tr( "This algorithm outputs an atlas layout to a set of image files (e.g. PNG or JPEG images).\n\n"
65 "If a coverage layer is set, the selected layout's atlas settings exposed in this algorithm "
66 "will be overwritten. In this case, an empty filter or sort by expression will turn those "
67 "settings off." );
68}
69
70void QgsLayoutAtlasToImageAlgorithm::initAlgorithm( const QVariantMap & )
71{
72 addParameter( new QgsProcessingParameterLayout( QStringLiteral( "LAYOUT" ), QObject::tr( "Atlas layout" ) ) );
73
74 addParameter( new QgsProcessingParameterVectorLayer( QStringLiteral( "COVERAGE_LAYER" ), QObject::tr( "Coverage layer" ), QList<int>(), QVariant(), true ) );
75 addParameter( new QgsProcessingParameterExpression( QStringLiteral( "FILTER_EXPRESSION" ), QObject::tr( "Filter expression" ), QString(), QStringLiteral( "COVERAGE_LAYER" ), true ) );
76 addParameter( new QgsProcessingParameterExpression( QStringLiteral( "SORTBY_EXPRESSION" ), QObject::tr( "Sort expression" ), QString(), QStringLiteral( "COVERAGE_LAYER" ), true ) );
77 addParameter( new QgsProcessingParameterBoolean( QStringLiteral( "SORTBY_REVERSE" ), QObject::tr( "Reverse sort order (used when a sort expression is provided)" ), false ) );
78
79 addParameter( new QgsProcessingParameterExpression( QStringLiteral( "FILENAME_EXPRESSION" ), QObject::tr( "Output filename expression" ), QStringLiteral( "'output_'||@atlas_featurenumber" ), QStringLiteral( "COVERAGE_LAYER" ) ) );
80 addParameter( new QgsProcessingParameterFile( QStringLiteral( "FOLDER" ), QObject::tr( "Output folder" ), Qgis::ProcessingFileParameterBehavior::Folder ) );
81
82
83 auto layersParam = std::make_unique<QgsProcessingParameterMultipleLayers>( QStringLiteral( "LAYERS" ), QObject::tr( "Map layers to assign to unlocked map item(s)" ), Qgis::ProcessingSourceType::MapLayer, QVariant(), true );
84 layersParam->setFlags( layersParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
85 addParameter( layersParam.release() );
86
87 QStringList imageFormats;
88 const QList<QByteArray> supportedImageFormats { QImageWriter::supportedImageFormats() };
89 for ( const QByteArray &format : supportedImageFormats )
90 {
91 if ( format == QByteArray( "svg" ) )
92 continue;
93 imageFormats << QString( format );
94 }
95 auto extensionParam = std::make_unique<QgsProcessingParameterEnum>( QStringLiteral( "EXTENSION" ), QObject::tr( "Image format" ), imageFormats, false, imageFormats.indexOf( QLatin1String( "png" ) ) );
96 extensionParam->setFlags( extensionParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
97 addParameter( extensionParam.release() );
98
99 auto dpiParam = std::make_unique<QgsProcessingParameterNumber>( QStringLiteral( "DPI" ), QObject::tr( "DPI (leave blank for default layout DPI)" ), Qgis::ProcessingNumberParameterType::Double, QVariant(), true, 0 );
100 dpiParam->setFlags( dpiParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
101 addParameter( dpiParam.release() );
102
103 auto appendGeorefParam = std::make_unique<QgsProcessingParameterBoolean>( QStringLiteral( "GEOREFERENCE" ), QObject::tr( "Generate world file" ), true );
104 appendGeorefParam->setFlags( appendGeorefParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
105 addParameter( appendGeorefParam.release() );
106
107 auto exportRDFParam = std::make_unique<QgsProcessingParameterBoolean>( QStringLiteral( "INCLUDE_METADATA" ), QObject::tr( "Export RDF metadata (title, author, etc.)" ), true );
108 exportRDFParam->setFlags( exportRDFParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
109 addParameter( exportRDFParam.release() );
110
111 auto antialias = std::make_unique<QgsProcessingParameterBoolean>( QStringLiteral( "ANTIALIAS" ), QObject::tr( "Enable antialiasing" ), true );
112 antialias->setFlags( antialias->flags() | Qgis::ProcessingParameterFlag::Advanced );
113 addParameter( antialias.release() );
114}
115
116Qgis::ProcessingAlgorithmFlags QgsLayoutAtlasToImageAlgorithm::flags() const
117{
119}
120
121QgsLayoutAtlasToImageAlgorithm *QgsLayoutAtlasToImageAlgorithm::createInstance() const
122{
123 return new QgsLayoutAtlasToImageAlgorithm();
124}
125
126QVariantMap QgsLayoutAtlasToImageAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
127{
128 // this needs to be done in main thread, layouts are not thread safe
129 QgsPrintLayout *l = parameterAsLayout( parameters, QStringLiteral( "LAYOUT" ), context );
130 if ( !l )
131 throw QgsProcessingException( QObject::tr( "Cannot find layout with name \"%1\"" ).arg( parameters.value( QStringLiteral( "LAYOUT" ) ).toString() ) );
132
133 std::unique_ptr<QgsPrintLayout> layout( l->clone() );
134 QgsLayoutAtlas *atlas = layout->atlas();
135
136 QString expression, error;
137 QgsVectorLayer *layer = parameterAsVectorLayer( parameters, QStringLiteral( "COVERAGE_LAYER" ), context );
138 if ( layer )
139 {
140 atlas->setEnabled( true );
141 atlas->setCoverageLayer( layer );
142
143 expression = parameterAsString( parameters, QStringLiteral( "FILTER_EXPRESSION" ), context );
144 atlas->setFilterExpression( expression, error );
145 atlas->setFilterFeatures( !expression.isEmpty() && error.isEmpty() );
146 if ( !expression.isEmpty() && !error.isEmpty() )
147 {
148 throw QgsProcessingException( QObject::tr( "Error setting atlas filter expression" ) );
149 }
150 error.clear();
151
152 expression = parameterAsString( parameters, QStringLiteral( "SORTBY_EXPRESSION" ), context );
153 if ( !expression.isEmpty() )
154 {
155 const bool sortByReverse = parameterAsBool( parameters, QStringLiteral( "SORTBY_REVERSE" ), context );
156 atlas->setSortFeatures( true );
157 atlas->setSortExpression( expression );
158 atlas->setSortAscending( !sortByReverse );
159 }
160 else
161 {
162 atlas->setSortFeatures( false );
163 }
164 }
165 else if ( !atlas->enabled() )
166 {
167 throw QgsProcessingException( QObject::tr( "Layout being export doesn't have an enabled atlas" ) );
168 }
169
170 expression = parameterAsString( parameters, QStringLiteral( "FILENAME_EXPRESSION" ), context );
171 atlas->setFilenameExpression( expression, error );
172 if ( !error.isEmpty() )
173 {
174 throw QgsProcessingException( QObject::tr( "Error setting atlas filename expression" ) );
175 }
176
177 const QString directory = parameterAsFileOutput( parameters, QStringLiteral( "FOLDER" ), context );
178 const QString fileName = QDir( directory ).filePath( QStringLiteral( "atlas" ) );
179
180 QStringList imageFormats;
181 const QList<QByteArray> supportedImageFormats { QImageWriter::supportedImageFormats() };
182 for ( const QByteArray &format : supportedImageFormats )
183 {
184 if ( format == QByteArray( "svg" ) )
185 continue;
186 imageFormats << QString( format );
187 }
188 const int idx = parameterAsEnum( parameters, QStringLiteral( "EXTENSION" ), context );
189 const QString extension = '.' + imageFormats.at( idx );
190
192
193 if ( parameters.value( QStringLiteral( "DPI" ) ).isValid() )
194 {
195 settings.dpi = parameterAsDouble( parameters, QStringLiteral( "DPI" ), context );
196 }
197
198 settings.exportMetadata = parameterAsBool( parameters, QStringLiteral( "INCLUDE_METADATA" ), context );
199 settings.generateWorldFile = parameterAsBool( parameters, QStringLiteral( "GEOREFERENCE" ), context );
200
201 if ( parameterAsBool( parameters, QStringLiteral( "ANTIALIAS" ), context ) )
203 else
204 settings.flags = settings.flags & ~static_cast< int >( Qgis::LayoutRenderFlag::Antialiasing );
205
206 settings.predefinedMapScales = QgsLayoutUtils::predefinedScales( layout.get() );
207
208 const QList<QgsMapLayer *> layers = parameterAsLayerList( parameters, QStringLiteral( "LAYERS" ), context );
209 if ( layers.size() > 0 )
210 {
211 const QList<QGraphicsItem *> items = layout->items();
212 for ( QGraphicsItem *graphicsItem : items )
213 {
214 QgsLayoutItem *item = dynamic_cast<QgsLayoutItem *>( graphicsItem );
215 QgsLayoutItemMap *map = dynamic_cast<QgsLayoutItemMap *>( item );
216 if ( map && !map->followVisibilityPreset() && !map->keepLayerSet() )
217 {
218 map->setKeepLayerSet( true );
219 map->setLayers( layers );
220 }
221 }
222 }
223
224 if ( atlas->updateFeatures() )
225 {
226 feedback->pushInfo( QObject::tr( "Exporting %n atlas feature(s)", "", atlas->count() ) );
227 switch ( QgsLayoutExporter::exportToImage( atlas, fileName, extension, settings, error, feedback ) )
228 {
230 {
231 feedback->pushInfo( QObject::tr( "Successfully exported layout to %1" ).arg( QDir::toNativeSeparators( directory ) ) );
232 break;
233 }
234
236 throw QgsProcessingException( !error.isEmpty() ? error : QObject::tr( "Cannot write to %1.\n\nThis file may be open in another application." ).arg( QDir::toNativeSeparators( directory ) ) );
237
239 throw QgsProcessingException( !error.isEmpty() ? error : QObject::tr( "Trying to create the image "
240 "resulted in a memory overflow.\n\n"
241 "Please try a lower resolution or a smaller paper size." ) );
242
244 throw QgsProcessingException( !error.isEmpty() ? error : QObject::tr( "Error encountered while exporting atlas." ) );
245
249 // no meaning for imageexports, will not be encountered
250 break;
251 }
252 }
253 else
254 {
255 feedback->reportError( QObject::tr( "No atlas features found" ) );
256 }
257
258 feedback->setProgress( 100 );
259
260 QVariantMap outputs;
261 outputs.insert( QStringLiteral( "FOLDER" ), directory );
262 return outputs;
263}
264
@ MapLayer
Any map layer type (raster, vector, mesh, point cloud, annotation or plugin layer).
Definition qgis.h:3532
@ Folder
Parameter is a folder.
Definition qgis.h:3790
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3609
@ NoThreading
Algorithm is not thread safe and cannot be run in a background thread, e.g. for algorithms which mani...
Definition qgis.h:3588
@ RequiresProject
The algorithm requires that a valid QgsProject is available from the processing context in order to e...
Definition qgis.h:3596
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Definition qgis.h:3763
@ Double
Double/float values.
Definition qgis.h:3804
@ Antialiasing
Use antialiasing when drawing items.
Definition qgis.h:5240
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:61
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.