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