QGIS API Documentation 3.99.0-Master (21b3aa880ba)
Loading...
Searching...
No Matches
qgsalgorithmlayouttoimage.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmlayouttoimage.cpp
3 ---------------------
4 begin : June 2020
5 copyright : (C) 2020 by Nyall Dawson
6 email : nyall dot dawson 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 "qgslayoutexporter.h"
22#include "qgslayoutitemmap.h"
23#include "qgsprintlayout.h"
25
26#include <QImageWriter>
27
29
30QString QgsLayoutToImageAlgorithm::name() const
31{
32 return QStringLiteral( "printlayouttoimage" );
33}
34
35QString QgsLayoutToImageAlgorithm::displayName() const
36{
37 return QObject::tr( "Export print layout as image" );
38}
39
40QStringList QgsLayoutToImageAlgorithm::tags() const
41{
42 return QObject::tr( "layout,composer,composition,save,png,jpeg,jpg" ).split( ',' );
43}
44
45QString QgsLayoutToImageAlgorithm::group() const
46{
47 return QObject::tr( "Cartography" );
48}
49
50QString QgsLayoutToImageAlgorithm::groupId() const
51{
52 return QStringLiteral( "cartography" );
53}
54
55QString QgsLayoutToImageAlgorithm::shortDescription() const
56{
57 return QObject::tr( "Exports a print layout as an image." );
58}
59
60QString QgsLayoutToImageAlgorithm::shortHelpString() const
61{
62 return QObject::tr( "This algorithm outputs a print layout as an image file (e.g. PNG or JPEG images)." );
63}
64
65void QgsLayoutToImageAlgorithm::initAlgorithm( const QVariantMap & )
66{
67 addParameter( new QgsProcessingParameterLayout( QStringLiteral( "LAYOUT" ), QObject::tr( "Print layout" ) ) );
68
69 auto layersParam = std::make_unique<QgsProcessingParameterMultipleLayers>( QStringLiteral( "LAYERS" ), QObject::tr( "Map layers to assign to unlocked map item(s)" ), Qgis::ProcessingSourceType::MapLayer, QVariant(), true );
70 layersParam->setFlags( layersParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
71 addParameter( layersParam.release() );
72
73 auto dpiParam = std::make_unique<QgsProcessingParameterNumber>( QStringLiteral( "DPI" ), QObject::tr( "DPI (leave blank for default layout DPI)" ), Qgis::ProcessingNumberParameterType::Double, QVariant(), true, 0 );
74 dpiParam->setFlags( dpiParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
75 addParameter( dpiParam.release() );
76
77 auto appendGeorefParam = std::make_unique<QgsProcessingParameterBoolean>( QStringLiteral( "GEOREFERENCE" ), QObject::tr( "Generate world file" ), true );
78 appendGeorefParam->setFlags( appendGeorefParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
79 addParameter( appendGeorefParam.release() );
80
81 auto exportRDFParam = std::make_unique<QgsProcessingParameterBoolean>( QStringLiteral( "INCLUDE_METADATA" ), QObject::tr( "Export RDF metadata (title, author, etc.)" ), true );
82 exportRDFParam->setFlags( exportRDFParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
83 addParameter( exportRDFParam.release() );
84
85 auto antialias = std::make_unique<QgsProcessingParameterBoolean>( QStringLiteral( "ANTIALIAS" ), QObject::tr( "Enable antialiasing" ), true );
86 antialias->setFlags( antialias->flags() | Qgis::ProcessingParameterFlag::Advanced );
87 addParameter( antialias.release() );
88
89 QStringList imageFilters;
90 const auto supportedImageFormats { QImageWriter::supportedImageFormats() };
91 for ( const QByteArray &format : supportedImageFormats )
92 {
93 if ( format == "svg" )
94 continue;
95
96 const QString longName = format.toUpper() + QObject::tr( " format" );
97 const QString glob = QStringLiteral( "*." ) + format;
98
99 if ( format == "png" && !imageFilters.empty() )
100 imageFilters.insert( 0, QStringLiteral( "%1 (%2 %3)" ).arg( longName, glob.toLower(), glob.toUpper() ) );
101 else
102 imageFilters.append( QStringLiteral( "%1 (%2 %3)" ).arg( longName, glob.toLower(), glob.toUpper() ) );
103 }
104
105 addParameter( new QgsProcessingParameterFileDestination( QStringLiteral( "OUTPUT" ), QObject::tr( "Image file" ), imageFilters.join( QLatin1String( ";;" ) ) ) );
106}
107
108Qgis::ProcessingAlgorithmFlags QgsLayoutToImageAlgorithm::flags() const
109{
111}
112
113QgsLayoutToImageAlgorithm *QgsLayoutToImageAlgorithm::createInstance() const
114{
115 return new QgsLayoutToImageAlgorithm();
116}
117
118QVariantMap QgsLayoutToImageAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
119{
120 // this needs to be done in main thread, layouts are not thread safe
121 QgsPrintLayout *l = parameterAsLayout( parameters, QStringLiteral( "LAYOUT" ), context );
122 if ( !l )
123 throw QgsProcessingException( QObject::tr( "Cannot find layout with name \"%1\"" ).arg( parameters.value( QStringLiteral( "LAYOUT" ) ).toString() ) );
124 std::unique_ptr<QgsPrintLayout> layout( l->clone() );
125
126 const QList<QgsMapLayer *> layers = parameterAsLayerList( parameters, QStringLiteral( "LAYERS" ), context );
127 if ( layers.size() > 0 )
128 {
129 const QList<QGraphicsItem *> items = layout->items();
130 for ( QGraphicsItem *graphicsItem : items )
131 {
132 QgsLayoutItem *item = dynamic_cast<QgsLayoutItem *>( graphicsItem );
133 QgsLayoutItemMap *map = dynamic_cast<QgsLayoutItemMap *>( item );
134 if ( map && !map->followVisibilityPreset() && !map->keepLayerSet() )
135 {
136 map->setKeepLayerSet( true );
137 map->setLayers( layers );
138 }
139 }
140 }
141
142 const QString dest = parameterAsFileOutput( parameters, QStringLiteral( "OUTPUT" ), context );
143
144 QgsLayoutExporter exporter( layout.get() );
146
147 if ( parameters.value( QStringLiteral( "DPI" ) ).isValid() )
148 {
149 settings.dpi = parameterAsDouble( parameters, QStringLiteral( "DPI" ), context );
150 }
151
152 settings.exportMetadata = parameterAsBool( parameters, QStringLiteral( "INCLUDE_METADATA" ), context );
153 settings.generateWorldFile = parameterAsBool( parameters, QStringLiteral( "GEOREFERENCE" ), context );
154
155 if ( parameterAsBool( parameters, QStringLiteral( "ANTIALIAS" ), context ) )
157 else
158 settings.flags = settings.flags & ~static_cast< int >( Qgis::LayoutRenderFlag::Antialiasing );
159
160 switch ( exporter.exportToImage( dest, settings ) )
161 {
163 {
164 feedback->pushInfo( QObject::tr( "Successfully exported layout to %1" ).arg( QDir::toNativeSeparators( dest ) ) );
165 break;
166 }
167
169 throw QgsProcessingException( !exporter.errorMessage().isEmpty() ? exporter.errorMessage() : QObject::tr( "Cannot write to %1.\n\nThis file may be open in another application." ).arg( QDir::toNativeSeparators( dest ) ) );
170
172 throw QgsProcessingException( !exporter.errorMessage().isEmpty() ? exporter.errorMessage() : QObject::tr( "Trying to create the image "
173 "resulted in a memory overflow.\n\n"
174 "Please try a lower resolution or a smaller paper size." ) );
175
180 // no meaning for imageexports, will not be encountered
181 break;
182 }
183
184 feedback->setProgress( 100 );
185
186 QVariantMap outputs;
187 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
188 return outputs;
189}
190
@ MapLayer
Any map layer type (raster, vector, mesh, point cloud, annotation or plugin layer).
Definition qgis.h:3532
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
Handles rendering and exports of layouts to various formats.
@ 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.
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.
A generic file based destination parameter, for specifying the destination path for a file (non-map l...
A print layout parameter, allowing users to select a print layout.
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.