QGIS API Documentation 3.99.0-Master (09f76ad7019)
Loading...
Searching...
No Matches
qgsalgorithmlayouttopdf.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmlayouttopdf.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 <QString>
27
28using namespace Qt::StringLiterals;
29
31
32QString QgsLayoutToPdfAlgorithm::name() const
33{
34 return u"printlayouttopdf"_s;
35}
36
37QString QgsLayoutToPdfAlgorithm::displayName() const
38{
39 return QObject::tr( "Export print layout as PDF" );
40}
41
42QStringList QgsLayoutToPdfAlgorithm::tags() const
43{
44 return QObject::tr( "layout,composer,composition,save" ).split( ',' );
45}
46
47QString QgsLayoutToPdfAlgorithm::group() const
48{
49 return QObject::tr( "Cartography" );
50}
51
52QString QgsLayoutToPdfAlgorithm::groupId() const
53{
54 return u"cartography"_s;
55}
56
57QString QgsLayoutToPdfAlgorithm::shortDescription() const
58{
59 return QObject::tr( "Exports a print layout as a PDF." );
60}
61
62QString QgsLayoutToPdfAlgorithm::shortHelpString() const
63{
64 return QObject::tr( "This algorithm outputs a print layout as a PDF file." );
65}
66
67void QgsLayoutToPdfAlgorithm::initAlgorithm( const QVariantMap & )
68{
69 addParameter( new QgsProcessingParameterLayout( u"LAYOUT"_s, QObject::tr( "Print layout" ) ) );
70
71 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 );
72 layersParam->setFlags( layersParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
73 addParameter( layersParam.release() );
74
75 auto dpiParam = std::make_unique<QgsProcessingParameterNumber>( u"DPI"_s, QObject::tr( "DPI (leave blank for default layout DPI)" ), Qgis::ProcessingNumberParameterType::Double, QVariant(), true, 0 );
76 dpiParam->setFlags( dpiParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
77 addParameter( dpiParam.release() );
78
79 auto forceVectorParam = std::make_unique<QgsProcessingParameterBoolean>( u"FORCE_VECTOR"_s, QObject::tr( "Always export as vectors" ), false );
80 forceVectorParam->setFlags( forceVectorParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
81 addParameter( forceVectorParam.release() );
82
83 auto forceRasterParam = std::make_unique<QgsProcessingParameterBoolean>( u"FORCE_RASTER"_s, QObject::tr( "Always export as raster" ), false );
84 forceRasterParam->setFlags( forceRasterParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
85 addParameter( forceRasterParam.release() );
86
87 auto appendGeorefParam = std::make_unique<QgsProcessingParameterBoolean>( u"GEOREFERENCE"_s, QObject::tr( "Append georeference information" ), true );
88 appendGeorefParam->setFlags( appendGeorefParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
89 addParameter( appendGeorefParam.release() );
90
91 auto exportRDFParam = std::make_unique<QgsProcessingParameterBoolean>( u"INCLUDE_METADATA"_s, QObject::tr( "Export RDF metadata (title, author, etc.)" ), true );
92 exportRDFParam->setFlags( exportRDFParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
93 addParameter( exportRDFParam.release() );
94
95 auto disableTiled = std::make_unique<QgsProcessingParameterBoolean>( u"DISABLE_TILED"_s, QObject::tr( "Disable tiled raster layer exports" ), false );
96 disableTiled->setFlags( disableTiled->flags() | Qgis::ProcessingParameterFlag::Advanced );
97 addParameter( disableTiled.release() );
98
99 auto simplify = std::make_unique<QgsProcessingParameterBoolean>( u"SIMPLIFY"_s, QObject::tr( "Simplify geometries to reduce output file size" ), true );
100 simplify->setFlags( simplify->flags() | Qgis::ProcessingParameterFlag::Advanced );
101 addParameter( simplify.release() );
102
103 const QStringList textExportOptions {
104 QObject::tr( "Always Export Text as Paths (Recommended)" ),
105 QObject::tr( "Always Export Text as Text Objects" ),
106 QObject::tr( "Prefer Exporting Text as Text Objects" )
107 };
108
109 auto textFormat = std::make_unique<QgsProcessingParameterEnum>( u"TEXT_FORMAT"_s, QObject::tr( "Text export" ), textExportOptions, false, 0 );
110 textFormat->setFlags( textFormat->flags() | Qgis::ProcessingParameterFlag::Advanced );
111 addParameter( textFormat.release() );
112
113 const QStringList imageCompressionOptions {
114 QObject::tr( "Lossy (JPEG)" ),
115 QObject::tr( "Lossless" )
116 };
117
118 auto imageCompression = std::make_unique<QgsProcessingParameterEnum>( u"IMAGE_COMPRESSION"_s, QObject::tr( "Image compression" ), imageCompressionOptions, false, 0 );
119 imageCompression->setFlags( imageCompression->flags() | Qgis::ProcessingParameterFlag::Advanced );
120 addParameter( imageCompression.release() );
121
122 auto layeredExport = std::make_unique<QgsProcessingParameterBoolean>( u"SEPARATE_LAYERS"_s, QObject::tr( "Export layers as separate PDF files" ), false );
123 layeredExport->setFlags( layeredExport->flags() | Qgis::ProcessingParameterFlag::Advanced );
124 addParameter( layeredExport.release() );
125
126 addParameter( new QgsProcessingParameterFileDestination( u"OUTPUT"_s, QObject::tr( "PDF file" ), QObject::tr( "PDF Format" ) + " (*.pdf *.PDF)" ) );
127}
128
129Qgis::ProcessingAlgorithmFlags QgsLayoutToPdfAlgorithm::flags() const
130{
132}
133
134QgsLayoutToPdfAlgorithm *QgsLayoutToPdfAlgorithm::createInstance() const
135{
136 return new QgsLayoutToPdfAlgorithm();
137}
138
139QVariantMap QgsLayoutToPdfAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
140{
141 // this needs to be done in main thread, layouts are not thread safe
142 QgsPrintLayout *l = parameterAsLayout( parameters, u"LAYOUT"_s, context );
143 if ( !l )
144 throw QgsProcessingException( QObject::tr( "Cannot find layout with name \"%1\"" ).arg( parameters.value( u"LAYOUT"_s ).toString() ) );
145 std::unique_ptr<QgsPrintLayout> layout( l->clone() );
146
147 const QList<QgsMapLayer *> layers = parameterAsLayerList( parameters, u"LAYERS"_s, context );
148 if ( layers.size() > 0 )
149 {
150 const QList<QGraphicsItem *> items = layout->items();
151 for ( QGraphicsItem *graphicsItem : items )
152 {
153 QgsLayoutItem *item = dynamic_cast<QgsLayoutItem *>( graphicsItem );
154 QgsLayoutItemMap *map = dynamic_cast<QgsLayoutItemMap *>( item );
155 if ( map && !map->followVisibilityPreset() && !map->keepLayerSet() )
156 {
157 map->setKeepLayerSet( true );
158 map->setLayers( layers );
159 }
160 }
161 }
162
163 const QString dest = parameterAsFileOutput( parameters, u"OUTPUT"_s, context );
164
165 QgsLayoutExporter exporter( layout.get() );
167
168 if ( parameters.value( u"DPI"_s ).isValid() )
169 {
170 settings.dpi = parameterAsDouble( parameters, u"DPI"_s, context );
171 }
172
173 settings.forceVectorOutput = parameterAsBool( parameters, u"FORCE_VECTOR"_s, context );
174 settings.rasterizeWholeImage = parameterAsBool( parameters, u"FORCE_RASTER"_s, context );
175 settings.appendGeoreference = parameterAsBool( parameters, u"GEOREFERENCE"_s, context );
176 settings.exportMetadata = parameterAsBool( parameters, u"INCLUDE_METADATA"_s, context );
177 settings.simplifyGeometries = parameterAsBool( parameters, u"SIMPLIFY"_s, context );
178 const int textFormat = parameterAsEnum( parameters, u"TEXT_FORMAT"_s, context );
179 switch ( textFormat )
180 {
181 case 0:
183 break;
184 case 1:
186 break;
187 case 2:
189 break;
190 default:
191 break;
192 }
193 settings.exportLayersAsSeperateFiles = parameterAsBool( parameters, u"SEPARATE_LAYERS"_s, context ); //#spellok
194
195 if ( parameterAsBool( parameters, u"DISABLE_TILED"_s, context ) )
197 else
198 settings.flags = settings.flags & ~static_cast< int >( Qgis::LayoutRenderFlag::DisableTiledRasterLayerRenders );
199
200 if ( parameterAsEnum( parameters, u"IMAGE_COMPRESSION"_s, context ) == 1 )
202 else
203 settings.flags = settings.flags & ~static_cast< int >( Qgis::LayoutRenderFlag::LosslessImageRendering );
204
205 switch ( exporter.exportToPdf( dest, settings ) )
206 {
208 {
209 feedback->pushInfo( QObject::tr( "Successfully exported layout to %1" ).arg( QDir::toNativeSeparators( dest ) ) );
210 break;
211 }
212
214 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 ) ) );
215
217 throw QgsProcessingException( !exporter.errorMessage().isEmpty() ? exporter.errorMessage() : QObject::tr( "Could not create print device." ) );
218
220 throw QgsProcessingException( !exporter.errorMessage().isEmpty() ? exporter.errorMessage() : QObject::tr( "Exporting the PDF "
221 "resulted in a memory overflow.\n\n"
222 "Please try a lower resolution or a smaller paper size." ) );
223
227 // no meaning for PDF exports, will not be encountered
228 break;
229 }
230
231 feedback->setProgress( 100 );
232
233 QVariantMap outputs;
234 outputs.insert( u"OUTPUT"_s, dest );
235 return outputs;
236}
237
@ MapLayer
Any map layer type (raster, vector, mesh, point cloud, annotation or plugin layer).
Definition qgis.h:3603
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3680
@ PreferText
Render text as text objects, unless doing so results in rendering artifacts or poor quality rendering...
Definition qgis.h:2887
@ AlwaysOutlines
Always render text using path objects (AKA outlines/curves). This setting guarantees the best quality...
Definition qgis.h:2885
@ AlwaysText
Always render text as text objects. While this mode preserves text objects as text for post-processin...
Definition qgis.h:2886
@ 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
@ DisableTiledRasterLayerRenders
If set, then raster layers will not be drawn as separate tiles. This may improve the appearance in ex...
Definition qgis.h:5352
@ LosslessImageRendering
Render images losslessly whenever possible, instead of the default lossy jpeg rendering used for some...
Definition qgis.h:5354
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:63
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 PDF.
bool forceVectorOutput
Set to true to force vector object exports, even when the resultant appearance will differ from the l...
bool rasterizeWholeImage
Set to true to force whole layout to be rasterized while exporting.
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.
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.
bool exportLayersAsSeperateFiles
true if individual layers from the layout should be rendered to separate PDF files.
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....