28#include <QImageWriter>
31using namespace Qt::StringLiterals;
35QString QgsLayoutAtlasToImageAlgorithm::name()
const
37 return u
"atlaslayouttoimage"_s;
40QString QgsLayoutAtlasToImageAlgorithm::displayName()
const
42 return QObject::tr(
"Export atlas layout as image" );
45QStringList QgsLayoutAtlasToImageAlgorithm::tags()
const
47 return QObject::tr(
"layout,atlas,composer,composition,save,png,jpeg,jpg" ).split(
',' );
50QString QgsLayoutAtlasToImageAlgorithm::group()
const
52 return QObject::tr(
"Cartography" );
55QString QgsLayoutAtlasToImageAlgorithm::groupId()
const
57 return u
"cartography"_s;
60QString QgsLayoutAtlasToImageAlgorithm::shortDescription()
const
62 return QObject::tr(
"Exports an atlas layout as a set of images." );
65QString QgsLayoutAtlasToImageAlgorithm::shortHelpString()
const
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 "
75void QgsLayoutAtlasToImageAlgorithm::initAlgorithm(
const QVariantMap & )
82 addParameter(
new QgsProcessingParameterBoolean( u
"SORTBY_REVERSE"_s, QObject::tr(
"Reverse sort order (used when a sort expression is provided)" ),
false ) );
84 addParameter(
new QgsProcessingParameterExpression( u
"FILENAME_EXPRESSION"_s, QObject::tr(
"Output filename expression" ), u
"'output_'||@atlas_featurenumber"_s, u
"COVERAGE_LAYER"_s ) );
89 = std::make_unique<QgsProcessingParameterMultipleLayers>( u
"LAYERS"_s, QObject::tr(
"Map layers to assign to unlocked map item(s)" ),
Qgis::ProcessingSourceType::MapLayer, QVariant(),
true );
91 addParameter( layersParam.release() );
93 QStringList imageFormats;
94 const QList<QByteArray> supportedImageFormats { QImageWriter::supportedImageFormats() };
95 for (
const QByteArray &format : supportedImageFormats )
97 if ( format == QByteArray(
"svg" ) )
99 imageFormats << QString( format );
101 auto extensionParam = std::make_unique<QgsProcessingParameterEnum>( u
"EXTENSION"_s, QObject::tr(
"Image format" ), imageFormats,
false, imageFormats.indexOf(
"png"_L1 ) );
103 addParameter( extensionParam.release() );
107 addParameter( dpiParam.release() );
109 auto appendGeorefParam = std::make_unique<QgsProcessingParameterBoolean>( u
"GEOREFERENCE"_s, QObject::tr(
"Generate world file" ),
true );
111 addParameter( appendGeorefParam.release() );
113 auto exportRDFParam = std::make_unique<QgsProcessingParameterBoolean>( u
"INCLUDE_METADATA"_s, QObject::tr(
"Export RDF metadata (title, author, etc.)" ),
true );
115 addParameter( exportRDFParam.release() );
117 auto antialias = std::make_unique<QgsProcessingParameterBoolean>( u
"ANTIALIAS"_s, QObject::tr(
"Enable antialiasing" ),
true );
119 addParameter( antialias.release() );
127QgsLayoutAtlasToImageAlgorithm *QgsLayoutAtlasToImageAlgorithm::createInstance()
const
129 return new QgsLayoutAtlasToImageAlgorithm();
135 QgsPrintLayout *l = parameterAsLayout( parameters, u
"LAYOUT"_s, context );
137 throw QgsProcessingException( QObject::tr(
"Cannot find layout with name \"%1\"" ).arg( parameters.value( u
"LAYOUT"_s ).toString() ) );
139 std::unique_ptr<QgsPrintLayout> layout( l->
clone() );
142 QString expression, error;
143 QgsVectorLayer *layer = parameterAsVectorLayer( parameters, u
"COVERAGE_LAYER"_s, context );
149 expression = parameterAsString( parameters, u
"FILTER_EXPRESSION"_s, context );
152 if ( !expression.isEmpty() && !error.isEmpty() )
158 expression = parameterAsString( parameters, u
"SORTBY_EXPRESSION"_s, context );
159 if ( !expression.isEmpty() )
161 const bool sortByReverse = parameterAsBool( parameters, u
"SORTBY_REVERSE"_s, context );
176 expression = parameterAsString( parameters, u
"FILENAME_EXPRESSION"_s, context );
178 if ( !error.isEmpty() )
183 const QString directory = parameterAsFileOutput( parameters, u
"FOLDER"_s, context );
184 const QString fileName = QDir( directory ).filePath( u
"atlas"_s );
186 QStringList imageFormats;
187 const QList<QByteArray> supportedImageFormats { QImageWriter::supportedImageFormats() };
188 for (
const QByteArray &format : supportedImageFormats )
190 if ( format == QByteArray(
"svg" ) )
192 imageFormats << QString( format );
194 const int idx = parameterAsEnum( parameters, u
"EXTENSION"_s, context );
195 const QString extension =
'.' + imageFormats.at( idx );
199 if ( parameters.value( u
"DPI"_s ).isValid() )
201 settings.
dpi = parameterAsDouble( parameters, u
"DPI"_s, context );
204 settings.
exportMetadata = parameterAsBool( parameters, u
"INCLUDE_METADATA"_s, context );
205 settings.
generateWorldFile = parameterAsBool( parameters, u
"GEOREFERENCE"_s, context );
207 if ( parameterAsBool( parameters, u
"ANTIALIAS"_s, context ) )
214 const QList<QgsMapLayer *> layers = parameterAsLayerList( parameters, u
"LAYERS"_s, context );
215 if ( layers.size() > 0 )
217 const QList<QGraphicsItem *> items = layout->items();
218 for ( QGraphicsItem *graphicsItem : items )
232 feedback->
pushInfo( QObject::tr(
"Exporting %n atlas feature(s)",
"", atlas->
count() ) );
237 feedback->
pushInfo( QObject::tr(
"Successfully exported layout to %1" ).arg( QDir::toNativeSeparators( directory ) ) );
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 ) ) );
246 !error.isEmpty() ? error
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."
255 throw QgsProcessingException( !error.isEmpty() ? error : QObject::tr(
"Error encountered while exporting atlas." ) );
266 feedback->
reportError( QObject::tr(
"No atlas features found" ) );
272 outputs.insert( u
"FOLDER"_s, directory );
@ MapLayer
Any map layer type (raster, vector, mesh, point cloud, annotation or plugin layer).
@ Folder
Parameter is a folder.
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
@ NoThreading
Algorithm is not thread safe and cannot be run in a background thread, e.g. for algorithms which mani...
@ RequiresProject
The algorithm requires that a valid QgsProject is available from the processing context in order to e...
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
@ Double
Double/float values.
@ Antialiasing
Use antialiasing when drawing items.
void setProgress(double progress)
Sets the current progress for the feedback object.
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.