QGIS API Documentation  3.22.4-Białowieża (ce8e65e95e)
qgsalgorithmlayoutatlastopdf.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsalgorithmlayoutatlastopdf.cpp
3  ---------------------
4  begin : August 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 #include "qgslayout.h"
20 #include "qgslayoutatlas.h"
21 #include "qgslayoutitemmap.h"
22 #include "qgslayoututils.h"
23 #include "qgsprintlayout.h"
24 #include "qgsprocessingoutputs.h"
25 #include "qgslayoutexporter.h"
26 
28 
29 QString QgsLayoutAtlasToPdfAlgorithm::name() const
30 {
31  return QStringLiteral( "atlaslayouttopdf" );
32 }
33 
34 QString QgsLayoutAtlasToPdfAlgorithm::displayName() const
35 {
36  return QObject::tr( "Export atlas layout as PDF" );
37 }
38 
39 QStringList QgsLayoutAtlasToPdfAlgorithm::tags() const
40 {
41  return QObject::tr( "layout,atlas,composer,composition,save" ).split( ',' );
42 }
43 
44 QString QgsLayoutAtlasToPdfAlgorithm::group() const
45 {
46  return QObject::tr( "Cartography" );
47 }
48 
49 QString QgsLayoutAtlasToPdfAlgorithm::groupId() const
50 {
51  return QStringLiteral( "cartography" );
52 }
53 
54 QString QgsLayoutAtlasToPdfAlgorithm::shortDescription() const
55 {
56  return QObject::tr( "Exports an atlas layout as a PDF." );
57 }
58 
59 QString QgsLayoutAtlasToPdfAlgorithm::shortHelpString() const
60 {
61  return QObject::tr( "This algorithm outputs an atlas layout as a PDF file.\n\n"
62  "If a coverage layer is set, the selected layout's atlas settings exposed in this algorithm "
63  "will be overwritten. In this case, an empty filter or sort by expression will turn those "
64  "settings off." );
65 }
66 
67 void QgsLayoutAtlasToPdfAlgorithm::initAlgorithm( const QVariantMap & )
68 {
69  addParameter( new QgsProcessingParameterLayout( QStringLiteral( "LAYOUT" ), QObject::tr( "Atlas layout" ) ) );
70 
71  addParameter( new QgsProcessingParameterVectorLayer( QStringLiteral( "COVERAGE_LAYER" ), QObject::tr( "Coverage layer" ), QList< int >(), QVariant(), true ) );
72  addParameter( new QgsProcessingParameterExpression( QStringLiteral( "FILTER_EXPRESSION" ), QObject::tr( "Filter expression" ), QString(), QStringLiteral( "COVERAGE_LAYER" ), true ) );
73  addParameter( new QgsProcessingParameterExpression( QStringLiteral( "SORTBY_EXPRESSION" ), QObject::tr( "Sort expression" ), QString(), QStringLiteral( "COVERAGE_LAYER" ), true ) );
74  addParameter( new QgsProcessingParameterBoolean( QStringLiteral( "SORTBY_REVERSE" ), QObject::tr( "Reverse sort order (used when a sort expression is provided)" ), false, true ) );
75 
76  addParameter( new QgsProcessingParameterFileDestination( QStringLiteral( "OUTPUT" ), QObject::tr( "PDF file" ), QObject::tr( "PDF Format" ) + " (*.pdf *.PDF)" ) );
77 
78  std::unique_ptr< QgsProcessingParameterMultipleLayers > layersParam = std::make_unique< QgsProcessingParameterMultipleLayers>( QStringLiteral( "LAYERS" ), QObject::tr( "Map layers to assign to unlocked map item(s)" ), QgsProcessing::TypeMapLayer, QVariant(), true );
79  layersParam->setFlags( layersParam->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
80  addParameter( layersParam.release() );
81 
82  std::unique_ptr< QgsProcessingParameterNumber > dpiParam = std::make_unique< QgsProcessingParameterNumber >( QStringLiteral( "DPI" ), QObject::tr( "DPI (leave blank for default layout DPI)" ), QgsProcessingParameterNumber::Double, QVariant(), true, 0 );
83  dpiParam->setFlags( dpiParam->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
84  addParameter( dpiParam.release() );
85 
86  std::unique_ptr< QgsProcessingParameterBoolean > forceVectorParam = std::make_unique< QgsProcessingParameterBoolean >( QStringLiteral( "FORCE_VECTOR" ), QObject::tr( "Always export as vectors" ), false );
87  forceVectorParam->setFlags( forceVectorParam->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
88  addParameter( forceVectorParam.release() );
89 
90  std::unique_ptr< QgsProcessingParameterBoolean > appendGeorefParam = std::make_unique< QgsProcessingParameterBoolean >( QStringLiteral( "GEOREFERENCE" ), QObject::tr( "Append georeference information" ), true );
91  appendGeorefParam->setFlags( appendGeorefParam->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
92  addParameter( appendGeorefParam.release() );
93 
94  std::unique_ptr< QgsProcessingParameterBoolean > exportRDFParam = std::make_unique< QgsProcessingParameterBoolean >( QStringLiteral( "INCLUDE_METADATA" ), QObject::tr( "Export RDF metadata (title, author, etc.)" ), true );
95  exportRDFParam->setFlags( exportRDFParam->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
96  addParameter( exportRDFParam.release() );
97 
98  std::unique_ptr< QgsProcessingParameterBoolean > disableTiled = std::make_unique< QgsProcessingParameterBoolean >( QStringLiteral( "DISABLE_TILED" ), QObject::tr( "Disable tiled raster layer exports" ), false );
99  disableTiled->setFlags( disableTiled->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
100  addParameter( disableTiled.release() );
101 
102  std::unique_ptr< QgsProcessingParameterBoolean > simplify = std::make_unique< QgsProcessingParameterBoolean >( QStringLiteral( "SIMPLIFY" ), QObject::tr( "Simplify geometries to reduce output file size" ), true );
103  simplify->setFlags( simplify->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
104  addParameter( simplify.release() );
105 
106  const QStringList textExportOptions
107  {
108  QObject::tr( "Always Export Text as Paths (Recommended)" ),
109  QObject::tr( "Always Export Text as Text Objects" )
110  };
111 
112  std::unique_ptr< QgsProcessingParameterEnum > textFormat = std::make_unique< QgsProcessingParameterEnum >( QStringLiteral( "TEXT_FORMAT" ), QObject::tr( "Text export" ), textExportOptions, false, 0 );
113  textFormat->setFlags( textFormat->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
114  addParameter( textFormat.release() );
115 }
116 
117 QgsProcessingAlgorithm::Flags QgsLayoutAtlasToPdfAlgorithm::flags() const
118 {
119  return QgsProcessingAlgorithm::flags() | FlagNoThreading;
120 }
121 
122 QgsLayoutAtlasToPdfAlgorithm *QgsLayoutAtlasToPdfAlgorithm::createInstance() const
123 {
124  return new QgsLayoutAtlasToPdfAlgorithm();
125 }
126 
127 QVariantMap QgsLayoutAtlasToPdfAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
128 {
129  // this needs to be done in main thread, layouts are not thread safe
130  QgsPrintLayout *l = parameterAsLayout( parameters, QStringLiteral( "LAYOUT" ), context );
131  if ( !l )
132  throw QgsProcessingException( QObject::tr( "Cannot find layout with name \"%1\"" ).arg( parameters.value( QStringLiteral( "LAYOUT" ) ).toString() ) );
133 
134  std::unique_ptr< QgsPrintLayout > layout( l->clone() );
135  QgsLayoutAtlas *atlas = layout->atlas();
136 
137  QString expression, error;
138  QgsVectorLayer *layer = parameterAsVectorLayer( parameters, QStringLiteral( "COVERAGE_LAYER" ), context );
139  if ( layer )
140  {
141  atlas->setEnabled( true );
142  atlas->setCoverageLayer( layer );
143 
144  expression = parameterAsString( parameters, QStringLiteral( "FILTER_EXPRESSION" ), context );
145  atlas->setFilterExpression( expression, error );
146  atlas->setFilterFeatures( !expression.isEmpty() && error.isEmpty() );
147  if ( !expression.isEmpty() && !error.isEmpty() )
148  {
149  throw QgsProcessingException( QObject::tr( "Error setting atlas filter expression" ) );
150  }
151  error.clear();
152 
153  expression = parameterAsString( parameters, QStringLiteral( "SORTBY_EXPRESSION" ), context );
154  if ( !expression.isEmpty() )
155  {
156  const bool sortByReverse = parameterAsBool( parameters, QStringLiteral( "SORTBY_REVERSE" ), context );
157  atlas->setSortFeatures( true );
158  atlas->setSortExpression( expression );
159  atlas->setSortAscending( !sortByReverse );
160  }
161  else
162  {
163  atlas->setSortFeatures( false );
164  }
165  }
166  else if ( !atlas->enabled() )
167  {
168  throw QgsProcessingException( QObject::tr( "Layout being export doesn't have an enabled atlas" ) );
169  }
170 
171  const QgsLayoutExporter exporter( layout.get() );
173 
174  if ( parameters.value( QStringLiteral( "DPI" ) ).isValid() )
175  {
176  settings.dpi = parameterAsDouble( parameters, QStringLiteral( "DPI" ), context );
177  }
178  settings.forceVectorOutput = parameterAsBool( parameters, QStringLiteral( "FORCE_VECTOR" ), context );
179  settings.appendGeoreference = parameterAsBool( parameters, QStringLiteral( "GEOREFERENCE" ), context );
180  settings.exportMetadata = parameterAsBool( parameters, QStringLiteral( "INCLUDE_METADATA" ), context );
181  settings.simplifyGeometries = parameterAsBool( parameters, QStringLiteral( "SIMPLIFY" ), context );
182  settings.textRenderFormat = parameterAsEnum( parameters, QStringLiteral( "TEXT_FORMAT" ), context ) == 0 ? Qgis::TextRenderFormat::AlwaysOutlines : Qgis::TextRenderFormat::AlwaysText;
183 
184  if ( parameterAsBool( parameters, QStringLiteral( "DISABLE_TILED" ), context ) )
186  else
187  settings.flags = settings.flags & ~QgsLayoutRenderContext::FlagDisableTiledRasterLayerRenders;
188 
189  settings.predefinedMapScales = QgsLayoutUtils::predefinedScales( layout.get() );
190 
191  const QList< QgsMapLayer * > layers = parameterAsLayerList( parameters, QStringLiteral( "LAYERS" ), context );
192  if ( layers.size() > 0 )
193  {
194  const QList<QGraphicsItem *> items = layout->items();
195  for ( QGraphicsItem *graphicsItem : items )
196  {
197  QgsLayoutItem *item = dynamic_cast<QgsLayoutItem *>( graphicsItem );
198  QgsLayoutItemMap *map = dynamic_cast<QgsLayoutItemMap *>( item );
199  if ( map && !map->followVisibilityPreset() && !map->keepLayerSet() )
200  {
201  map->setKeepLayerSet( true );
202  map->setLayers( layers );
203  }
204  }
205  }
206 
207  const QString dest = parameterAsFileOutput( parameters, QStringLiteral( "OUTPUT" ), context );
208  if ( atlas->updateFeatures() )
209  {
210  feedback->pushInfo( QObject::tr( "Exporting %n atlas feature(s)", "", atlas->count() ) );
211  switch ( exporter.exportToPdf( atlas, dest, settings, error, feedback ) )
212  {
214  {
215  feedback->pushInfo( QObject::tr( "Successfully exported layout to %1" ).arg( QDir::toNativeSeparators( dest ) ) );
216  break;
217  }
218 
220  throw QgsProcessingException( QObject::tr( "Cannot write to %1.\n\nThis file may be open in another application." ).arg( QDir::toNativeSeparators( dest ) ) );
221 
223  throw QgsProcessingException( QObject::tr( "Could not create print device." ) );
224 
226  throw QgsProcessingException( QObject::tr( "Trying to create the image "
227  "resulted in a memory overflow.\n\n"
228  "Please try a lower resolution or a smaller paper size." ) );
229 
231  throw QgsProcessingException( QObject::tr( "Error encountered while exporting atlas." ) );
232 
235  // no meaning for imageexports, will not be encountered
236  break;
237  }
238  }
239  else
240  {
241  feedback->reportError( QObject::tr( "No atlas features found" ) );
242  }
243 
244  feedback->setProgress( 100 );
245 
246  QVariantMap outputs;
247  outputs.insert( QStringLiteral( "OUTPUT" ), dest );
248  return outputs;
249 }
250 
252 
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition: qgsfeedback.h:63
Class used to render QgsLayout as an atlas, by iterating over the features from an associated vector ...
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.
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.
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.
Stores information relating to the current rendering settings for a layout.
@ FlagDisableTiledRasterLayerRenders
If set, then raster layers will not be drawn as separate tiles. This may improve the appearance in ex...
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 Flags 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.
Definition: qgsexception.h:83
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.
@ FlagAdvanced
Parameter is an advanced parameter which should be hidden from users by default.
An expression parameter for processing algorithms.
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.
A vector layer (with or without geometry) parameter for processing algorithms.
@ TypeMapLayer
Any map layer type (raster, vector, mesh, point cloud, annotation or plugin layer)
Definition: qgsprocessing.h:47
Represents a vector layer which manages a vector based data sets.
Contains settings relating to exporting layouts to PDF.
bool forceVectorOutput
Set to true to force vector object exports, even when the resultant appearance will differ from the l...
bool exportMetadata
Indicates whether PDF export should include metadata generated from the layout's project's metadata.
bool appendGeoreference
Indicates whether PDF export should append georeference data.
QgsLayoutRenderContext::Flags 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.
bool simplifyGeometries
Indicates whether vector geometries should be simplified to avoid redundant extraneous detail,...
Qgis::TextRenderFormat textRenderFormat
Text rendering format, which controls how text should be rendered in the export (e....