QGIS API Documentation 3.99.0-Master (26c88405ac0)
Loading...
Searching...
No Matches
qgslayoutexporter.h
Go to the documentation of this file.
1/***************************************************************************
2 qgslayoutexporter.h
3 -------------------
4 begin : October 2017
5 copyright : (C) 2017 by Nyall Dawson
6 email : nyall dot dawson at gmail dot com
7 ***************************************************************************/
8/***************************************************************************
9 * *
10 * This program is free software; you can redistribute it and/or modify *
11 * it under the terms of the GNU General Public License as published by *
12 * the Free Software Foundation; either version 2 of the License, or *
13 * (at your option) any later version. *
14 * *
15 ***************************************************************************/
16#ifndef QGSLAYOUTEXPORTER_H
17#define QGSLAYOUTEXPORTER_H
18
19#include "qgsconfig.h"
20
21#include <functional>
22
23#include "qgis_core.h"
24#include "qgslayoutitem.h"
27#include "qgsmargins.h"
28
29#include <QPdfWriter>
30#include <QPointer>
31#include <QRectF>
32#include <QSize>
33#include <QVector>
34
35#if defined( HAVE_QTPRINTER )
36#include <QPrinter>
37#endif
38
39class QgsLayout;
40class QPainter;
43class QgsFeedback;
47
53class CORE_EXPORT QgsLayoutExporter
54{
55
56 public:
57
60
63
66
69
72 {
74 QString directory;
75
77 QString baseName;
78
80 QString extension;
81
83 int page = 0;
84 };
85
90
91 virtual ~QgsLayoutExporter();
92
96 QgsLayout *layout() const;
97
106 void renderPage( QPainter *painter, int page ) const;
107
126 QImage renderPageToImage( int page, QSize imageSize = QSize(), double dpi = -1 ) const;
127
135 void renderRegion( QPainter *painter, const QRectF &region ) const;
136
153 QImage renderRegionToImage( const QRectF &region, QSize imageSize = QSize(), double dpi = -1 ) const;
154
155
167
170 {
172 : flags( Qgis::LayoutRenderFlag::Antialiasing | Qgis::LayoutRenderFlag::UseAdvancedEffects )
173 {}
174
176 double dpi = -1;
177
191
196 bool cropToContents = false;
197
203
211 QList< int > pages;
212
217 bool generateWorldFile = false;
218
225 bool exportMetadata = true;
226
231
237 QVector<qreal> predefinedMapScales;
238
244 int quality = -1;
245
246 };
247
258 ExportResult exportToImage( const QString &filePath, const QgsLayoutExporter::ImageExportSettings &settings );
259
260
271 static ExportResult exportToImage( QgsAbstractLayoutIterator *iterator, const QString &baseFilePath,
272 const QString &extension, const QgsLayoutExporter::ImageExportSettings &settings,
273 QString &error SIP_OUT, QgsFeedback *feedback = nullptr );
274
275
278 {
280 : flags( Qgis::LayoutRenderFlag::Antialiasing | Qgis::LayoutRenderFlag::UseAdvancedEffects )
281 {}
282
284 double dpi = -1;
285
292
300 bool forceVectorOutput = false;
301
308
315 bool exportMetadata = true;
316
321
329
337
349 bool writeGeoPdf = false;
350
364 bool exportLayersAsSeperateFiles = false; // TODO QGIS 4 fix typo //#spellok
365
375
388
395
404 QStringList exportThemes;
405
411 QVector<qreal> predefinedMapScales;
412 };
413
420 ExportResult exportToPdf( const QString &filePath, const QgsLayoutExporter::PdfExportSettings &settings );
421
433 static ExportResult exportToPdf( QgsAbstractLayoutIterator *iterator, const QString &fileName,
435 QString &error SIP_OUT, QgsFeedback *feedback = nullptr );
436
449 static ExportResult exportToPdfs( QgsAbstractLayoutIterator *iterator, const QString &baseFilePath,
451 QString &error SIP_OUT, QgsFeedback *feedback = nullptr );
452
453
456 {
458 : flags( Qgis::LayoutRenderFlag::Antialiasing | Qgis::LayoutRenderFlag::UseAdvancedEffects )
459 {}
460
462 double dpi = -1;
463
470
475
481 QVector<qreal> predefinedMapScales;
482
483 };
484
485#if defined( HAVE_QTPRINTER )
486 SIP_IF_FEATURE( HAVE_QTPRINTER )
487
488
494 ExportResult print( QPrinter &printer, const QgsLayoutExporter::PrintExportSettings &settings );
495
503 static ExportResult print( QgsAbstractLayoutIterator *iterator, QPrinter &printer,
505 QString &error SIP_OUT, QgsFeedback *feedback = nullptr );
506
507 SIP_END
508#endif
509
512 {
514 : flags( Qgis::LayoutRenderFlag::Antialiasing | Qgis::LayoutRenderFlag::UseAdvancedEffects )
515 {}
516
518 double dpi = -1;
519
527 bool forceVectorOutput = false;
528
533 bool cropToContents = false;
534
540
546 bool exportAsLayers = false;
547
557
564 bool exportMetadata = true;
565
570
578
586
592 QVector<qreal> predefinedMapScales;
593 };
594
601 ExportResult exportToSvg( const QString &filePath, const QgsLayoutExporter::SvgExportSettings &settings );
602
613 static ExportResult exportToSvg( QgsAbstractLayoutIterator *iterator, const QString &baseFilePath,
615 QString &error SIP_OUT, QgsFeedback *feedback = nullptr );
616
617
622 QString errorFile() const { return mErrorFileName; }
623
629 QString errorMessage() const { return mErrorMessage; }
630
638 QMap< QString, QgsLabelingResults * > labelingResults();
639
640#ifndef SIP_RUN
641
651 QMap< QString, QgsLabelingResults * > takeLabelingResults();
652#endif
653
669 bool georeferenceOutput( const QString &file, QgsLayoutItemMap *referenceMap = nullptr,
670 const QRectF &exportRegion = QRectF(), double dpi = -1 ) const;
671
678 void computeWorldFileParameters( double &a, double &b, double &c, double &d, double &e, double &f, double dpi = -1 ) const;
679
685 void computeWorldFileParameters( const QRectF &region, double &a, double &b, double &c, double &d, double &e, double &f, double dpi = -1 ) const;
686
695 static bool requiresRasterization( const QgsLayout *layout );
696
704 static bool containsAdvancedEffects( const QgsLayout *layout );
705
706 protected:
707
713 virtual QString generateFileName( const PageExportDetails &details ) const;
714
715 private:
716
717 QPointer< QgsLayout > mLayout;
718
719 void captureLabelingResults();
720 QMap< QString, QgsLabelingResults * > mLabelingResults;
721
722 mutable QString mErrorFileName;
723 mutable QString mErrorMessage;
724
725 QImage createImage( const ImageExportSettings &settings, int page, QRectF &bounds, bool &skipPage ) const;
726
731 static int firstPageToBeExported( QgsLayout *layout );
732
736 static bool saveImage( const QImage &image, const QString &imageFilename, const QString &imageFormat, QgsProject *projectForMetadata, int quality = -1 );
737
751 std::unique_ptr<double[]> computeGeoTransform( const QgsLayoutItemMap *referenceMap = nullptr, const QRectF &exportRegion = QRectF(), double dpi = -1 ) const;
752
754 void writeWorldFile( const QString &fileName, double a, double b, double c, double d, double e, double f ) const;
755
759 static void preparePrintAsPdf( QgsLayout *layout, QPdfWriter *device, const QString &filePath );
760
761 static void preparePrint( QgsLayout *layout, QPagedPaintDevice *device, bool setFirstPageSize = false );
762
766 ExportResult print( QPagedPaintDevice *device );
767
776 ExportResult printPrivate( QPagedPaintDevice *device, QPainter &painter, bool startNewPage = false, double dpi = -1, bool rasterize = false );
777
778 static void updatePrinterPageSize( QgsLayout *layout, QPagedPaintDevice *device, int page );
779
780 ExportResult renderToLayeredSvg( const SvgExportSettings &settings, double width, double height, int page, const QRectF &bounds,
781 const QString &filename, unsigned int svgLayerId, const QString &layerName,
782 QDomDocument &svg, QDomNode &svgDocRoot, bool includeMetadata ) const;
783
784 void appendMetadataToSvg( QDomDocument &svg ) const;
785
786 bool georeferenceOutputPrivate( const QString &file, QgsLayoutItemMap *referenceMap = nullptr,
787 const QRectF &exportRegion = QRectF(), double dpi = -1, bool includeGeoreference = true, bool includeMetadata = false ) const;
788
789 ExportResult handleLayeredExport( const QList<QGraphicsItem *> &items,
790 const std::function<QgsLayoutExporter::ExportResult( unsigned int layerId, const QgsLayoutItem::ExportLayerDetail &layerDetails )> &exportFunc,
791 const std::function<QString( QgsLayoutItem *item )> &getItemExportGroupFunc
792 );
793
794 // Returns PDF creator (used also as producer)
795 static QString getCreator();
796
797 // Set PDF XMP metadata on pdfWriter for given layout
798 static void setXmpMetadata( QPdfWriter *pdfWriter, QgsLayout *layout );
799
800 static QgsVectorSimplifyMethod createExportSimplifyMethod();
801 static QgsMaskRenderSettings createExportMaskSettings();
802 friend class TestQgsLayout;
804
805};
806
807#endif //QGSLAYOUTEXPORTER_H
808
809
810
Provides global constants and enumerations for use throughout the application.
Definition qgis.h:56
QFlags< LayoutRenderFlag > LayoutRenderFlags
Flags for controlling how a layout is rendered.
Definition qgis.h:5261
TextRenderFormat
Options for rendering text.
Definition qgis.h:2826
@ AlwaysOutlines
Always render text using path objects (AKA outlines/curves). This setting guarantees the best quality...
Definition qgis.h:2827
An abstract base class for QgsLayout based classes which can be exported by QgsLayoutExporter.
Base class for feedback objects to be used for cancellation of something running in a worker thread.
Definition qgsfeedback.h:44
Stores computed placement from labeling engine.
ExportResult exportToSvg(const QString &filePath, const QgsLayoutExporter::SvgExportSettings &settings)
Exports the layout as an SVG to the filePath, using the specified export settings.
ExportResult exportToImage(const QString &filePath, const QgsLayoutExporter::ImageExportSettings &settings)
Exports the layout to the filePath, using the specified export settings.
QString errorMessage() const
Returns a string describing the last error encountered during an export.
ExportResult exportToPdf(const QString &filePath, const QgsLayoutExporter::PdfExportSettings &settings)
Exports the layout as a PDF to the filePath, using the specified export settings.
QImage renderRegionToImage(const QRectF &region, QSize imageSize=QSize(), double dpi=-1) const
Renders a region of the layout to an image.
QgsLayout * layout() const
Returns the layout linked to this exporter.
static const QgsSettingsEntryBool * settingOpenAfterExportingPdf
Settings entry - Whether to automatically open pdfs after exporting them.
ExportResult
Result codes for exporting layouts.
@ 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.
static const QgsSettingsEntryInteger * settingImageQuality
Settings entry - Image quality for lossy formats.
QImage renderPageToImage(int page, QSize imageSize=QSize(), double dpi=-1) const
Renders a full page to an image.
QgsLayoutExporter(QgsLayout *layout)
Constructor for QgsLayoutExporter, for the specified layout.
friend class TestQgsLayoutExporter
static ExportResult exportToPdfs(QgsAbstractLayoutIterator *iterator, const QString &baseFilePath, const QgsLayoutExporter::PdfExportSettings &settings, QString &error, QgsFeedback *feedback=nullptr)
Exports a layout iterator to multiple PDF files, with the specified export settings.
QString errorFile() const
Returns the file name corresponding to the last error encountered during an export.
void renderPage(QPainter *painter, int page) const
Renders a full page to a destination painter.
static const QgsSettingsEntryBool * settingOpenAfterExportingImage
Settings entry - Whether to automatically open images after exporting them.
static const QgsSettingsEntryBool * settingOpenAfterExportingSvg
Settings entry - Whether to automatically open svgs after exporting them.
void renderRegion(QPainter *painter, const QRectF &region) const
Renders a region from the layout to a painter.
friend class TestQgsLayout
Layout graphical items for displaying a map.
Base class for graphical items within a QgsLayout.
Base class for layouts, which can contain items such as maps, labels, scalebars, etc.
Definition qgslayout.h:50
Defines the four margins of a rectangle.
Definition qgsmargins.h:38
Contains settings regarding how masks are calculated and handled during a map render.
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
Definition qgsproject.h:109
A boolean settings entry.
An integer settings entry.
Contains settings for simplifying geometries fetched from a vector layer.
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into c
#define SIP_SKIP
Definition qgis_sip.h:134
#define SIP_IF_FEATURE(feature)
Definition qgis_sip.h:189
#define SIP_OUT
Definition qgis_sip.h:58
#define SIP_END
Definition qgis_sip.h:216
Contains settings relating to exporting layouts to raster images.
QgsMargins cropMargins
Crop to content margins, in pixels.
QList< int > pages
List of specific pages to export, or an empty list to export all pages.
bool generateWorldFile
Set to true to generate an external world file alongside exported images.
QSize imageSize
Manual size in pixels for output image.
bool exportMetadata
Indicates whether image export should include metadata generated from the layout's project's metadata...
int quality
Image quality, typically used for JPEG compression (whose quality ranges from 1 to 100) if quality is...
Qgis::LayoutRenderFlags flags
Layout context flags, which control how the export will be created.
bool cropToContents
Set to true if image should be cropped so only parts of the layout containing items are exported.
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.
Contains details of a page being exported by the class.
QString baseName
Base part of filename (i.e. file name without extension or '.').
QString extension
File suffix/extension (without the leading '.').
int page
Page number, where 0 = first page.
Contains settings relating to exporting layouts to PDF.
bool useIso32000ExtensionFormatGeoreferencing
true if ISO3200 extension format georeferencing should be used.
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.
QStringList exportThemes
Optional list of map themes to export as Geospatial PDF layer groups.
bool includeGeoPdfFeatures
true if feature vector information (such as attributes) should be exported during Geospatial PDF expo...
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.
bool writeGeoPdf
true if geospatial PDF files should be created, instead of normal PDF files.
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 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,...
bool useOgcBestPracticeFormatGeoreferencing
true if OGC "best practice" format georeferencing should be used.
Qgis::TextRenderFormat textRenderFormat
Text rendering format, which controls how text should be rendered in the export (e....
Contains settings relating to printing layouts.
QVector< qreal > predefinedMapScales
A list of predefined scales to use with the layout.
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 rasterizeWholeImage
Set to true to force whole layout to be rasterized while exporting.
Contains settings relating to exporting layouts to SVG.
bool forceVectorOutput
Set to true to force vector object exports, even when the resultant appearance will differ from the l...
Qgis::LayoutRenderFlags flags
Layout context flags, which control how the export will be created.
Qgis::TextRenderFormat textRenderFormat
Text rendering format, which controls how text should be rendered in the export (e....
bool exportAsLayers
Set to true to export as a layered SVG file.
bool simplifyGeometries
Indicates whether vector geometries should be simplified to avoid redundant extraneous detail,...
bool exportMetadata
Indicates whether SVG export should include RDF metadata generated from the layout's project's metada...
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 exportLabelsToSeparateLayers
Set to true to export labels to separate layers (grouped by map layer) in layered SVG exports.
bool cropToContents
Set to true if image should be cropped so only parts of the layout containing items are exported.
QgsMargins cropMargins
Crop to content margins, in layout units.
Contains details of a particular export layer relating to a layout item.