33#include <QImageWriter>
35#include <QSvgGenerator>
44class LayoutContextPreviewSettingRestorer
48 LayoutContextPreviewSettingRestorer(
QgsLayout *layout )
50 , mPreviousSetting( layout->renderContext().mIsPreviewRender )
52 mLayout->renderContext().mIsPreviewRender =
false;
55 ~LayoutContextPreviewSettingRestorer()
57 mLayout->renderContext().mIsPreviewRender = mPreviousSetting;
60 LayoutContextPreviewSettingRestorer(
const LayoutContextPreviewSettingRestorer &other ) =
delete;
61 LayoutContextPreviewSettingRestorer &operator=(
const LayoutContextPreviewSettingRestorer &other ) =
delete;
65 bool mPreviousSetting =
false;
75 const QList< QgsLayoutGuide * > guides = mLayout->guides().guides();
78 mPrevVisibility.insert( guide, guide->item()->isVisible() );
79 guide->item()->setVisible(
false );
85 for (
auto it = mPrevVisibility.constBegin(); it != mPrevVisibility.constEnd(); ++it )
87 it.key()->item()->setVisible( it.value() );
91 LayoutGuideHider(
const LayoutGuideHider &other ) =
delete;
92 LayoutGuideHider &operator=(
const LayoutGuideHider &other ) =
delete;
96 QHash< QgsLayoutGuide *, bool > mPrevVisibility;
102 explicit LayoutItemHider(
const QList<QGraphicsItem *> &items )
104 mItemsToIterate.reserve( items.count() );
105 for ( QGraphicsItem *item : items )
107 const bool isVisible = item->isVisible();
108 mPrevVisibility[item] = isVisible;
110 mItemsToIterate.append( item );
112 layoutItem->setProperty(
"wasVisible", isVisible );
120 for (
auto it = mPrevVisibility.constBegin(); it != mPrevVisibility.constEnd(); ++it )
128 for (
auto it = mPrevVisibility.constBegin(); it != mPrevVisibility.constEnd(); ++it )
130 it.key()->setVisible( it.value() );
132 layoutItem->setProperty(
"wasVisible", QVariant() );
136 QList< QGraphicsItem * > itemsToIterate()
const {
return mItemsToIterate; }
138 LayoutItemHider(
const LayoutItemHider &other ) =
delete;
139 LayoutItemHider &operator=(
const LayoutItemHider &other ) =
delete;
143 QList<QGraphicsItem * > mItemsToIterate;
144 QHash<QGraphicsItem *, bool> mPrevVisibility;
161 qDeleteAll( mLabelingResults );
174 if ( mLayout->pageCollection()->pageCount() <= page || page < 0 )
185 LayoutContextPreviewSettingRestorer restorer( mLayout );
188 QRectF paperRect = QRectF( pageItem->pos().x(), pageItem->pos().y(), pageItem->rect().width(), pageItem->rect().height() );
197 if ( mLayout->pageCollection()->pageCount() <= page || page < 0 )
208 LayoutContextPreviewSettingRestorer restorer( mLayout );
211 QRectF paperRect = QRectF( pageItem->pos().x(), pageItem->pos().y(), pageItem->rect().width(), pageItem->rect().height() );
213 const double imageAspectRatio =
static_cast< double >( imageSize.width() ) / imageSize.height();
214 const double paperAspectRatio = paperRect.width() / paperRect.height();
215 if ( imageSize.isValid() && ( !
qgsDoubleNear( imageAspectRatio, paperAspectRatio, 0.008 ) ) )
220 QgsMessageLog::logMessage( QObject::tr(
"Ignoring custom image size because aspect ratio %1 does not match paper ratio %2" ).arg( QString::number( imageAspectRatio,
'g', 3 ), QString::number( paperAspectRatio,
'g', 3 ) ), QStringLiteral(
"Layout" ),
Qgis::MessageLevel::Warning );
228class LayoutItemCacheSettingRestorer
232 LayoutItemCacheSettingRestorer(
QgsLayout *layout )
235 const QList< QGraphicsItem * > items = mLayout->items();
236 for ( QGraphicsItem *item : items )
238 mPrevCacheMode.insert( item, item->cacheMode() );
239 item->setCacheMode( QGraphicsItem::NoCache );
243 ~LayoutItemCacheSettingRestorer()
245 for (
auto it = mPrevCacheMode.constBegin(); it != mPrevCacheMode.constEnd(); ++it )
247 it.key()->setCacheMode( it.value() );
251 LayoutItemCacheSettingRestorer(
const LayoutItemCacheSettingRestorer &other ) =
delete;
252 LayoutItemCacheSettingRestorer &operator=(
const LayoutItemCacheSettingRestorer &other ) =
delete;
256 QHash< QGraphicsItem *, QGraphicsItem::CacheMode > mPrevCacheMode;
263 QPaintDevice *paintDevice = painter->device();
264 if ( !paintDevice || !mLayout )
269 LayoutItemCacheSettingRestorer cacheRestorer( mLayout );
270 ( void )cacheRestorer;
271 LayoutContextPreviewSettingRestorer restorer( mLayout );
273 LayoutGuideHider guideHider( mLayout );
278 mLayout->render( painter, QRectF( 0, 0, paintDevice->width(), paintDevice->height() ), region );
286 LayoutContextPreviewSettingRestorer restorer( mLayout );
289 double resolution = mLayout->renderContext().dpi();
291 if ( imageSize.isValid() )
295 resolution = ( imageSize.width() / region.width()
296 + imageSize.height() / region.height() ) / 2.0 * oneInchInLayoutUnits;
304 int width = imageSize.isValid() ? imageSize.width()
305 :
static_cast< int >( resolution * region.width() / oneInchInLayoutUnits );
306 int height = imageSize.isValid() ? imageSize.height()
307 :
static_cast< int >( resolution * region.height() / oneInchInLayoutUnits );
309 QImage image( QSize( width, height ), QImage::Format_ARGB32 );
310 if ( !image.isNull() )
313 if ( width > 32768 || height > 32768 )
314 QgsMessageLog::logMessage( QObject::tr(
"Error: output width or height is larger than 32768 pixel, result will be clipped" ) );
315 image.setDotsPerMeterX(
static_cast< int >( std::round( resolution / 25.4 * 1000 ) ) );
316 image.setDotsPerMeterY(
static_cast< int>( std::round( resolution / 25.4 * 1000 ) ) );
317 image.fill( Qt::transparent );
318 QPainter imagePainter( &image );
320 if ( !imagePainter.isActive() )
328class LayoutContextSettingsRestorer
333 LayoutContextSettingsRestorer(
QgsLayout *layout )
335 , mPreviousDpi( layout->renderContext().dpi() )
336 , mPreviousFlags( layout->renderContext().flags() )
337 , mPreviousTextFormat( layout->renderContext().textRenderFormat() )
338 , mPreviousExportLayer( layout->renderContext().currentExportLayer() )
339 , mPreviousSimplifyMethod( layout->renderContext().simplifyMethod() )
340 , mPreviousMaskSettings( layout->renderContext().maskSettings() )
341 , mExportThemes( layout->renderContext().exportThemes() )
342 , mPredefinedScales( layout->renderContext().predefinedScales() )
347 ~LayoutContextSettingsRestorer()
349 mLayout->renderContext().setDpi( mPreviousDpi );
350 mLayout->renderContext().setFlags( mPreviousFlags );
351 mLayout->renderContext().setTextRenderFormat( mPreviousTextFormat );
353 mLayout->renderContext().setCurrentExportLayer( mPreviousExportLayer );
355 mLayout->renderContext().setSimplifyMethod( mPreviousSimplifyMethod );
356 mLayout->renderContext().setMaskSettings( mPreviousMaskSettings );
357 mLayout->renderContext().setExportThemes( mExportThemes );
358 mLayout->renderContext().setPredefinedScales( mPredefinedScales );
361 LayoutContextSettingsRestorer(
const LayoutContextSettingsRestorer &other ) =
delete;
362 LayoutContextSettingsRestorer &operator=(
const LayoutContextSettingsRestorer &other ) =
delete;
366 double mPreviousDpi = 0;
369 int mPreviousExportLayer = 0;
372 QStringList mExportThemes;
373 QVector< double > mPredefinedScales;
384 if ( settings.
dpi <= 0 )
385 settings.
dpi = mLayout->renderContext().dpi();
387 mErrorFileName.clear();
389 int worldFilePageNo = -1;
392 worldFilePageNo = referenceMap->page();
395 QFileInfo fi( filePath );
397 if ( !dir.exists( fi.absolutePath() ) )
399 dir.mkpath( fi.absolutePath() );
404 pageDetails.
baseName = fi.completeBaseName();
407 LayoutContextPreviewSettingRestorer restorer( mLayout );
409 LayoutContextSettingsRestorer dpiRestorer( mLayout );
411 mLayout->renderContext().setDpi( settings.
dpi );
412 mLayout->renderContext().setFlags( settings.
flags );
416 if ( settings.
pages.empty() )
418 for (
int page = 0; page < mLayout->pageCollection()->pageCount(); ++page )
423 for (
int page : std::as_const( settings.
pages ) )
425 if ( page >= 0 && page < mLayout->pageCollection()->pageCount() )
430 for (
int page : std::as_const( pages ) )
432 if ( !mLayout->pageCollection()->shouldExportPage( page ) )
439 QImage image = createImage( settings, page, bounds, skip );
444 pageDetails.
page = page;
447 if ( image.isNull() )
449 mErrorFileName = outputFilePath;
453 if ( !saveImage( image, outputFilePath, pageDetails.
extension, settings.
exportMetadata ? mLayout->project() : nullptr ) )
455 mErrorFileName = outputFilePath;
459 const bool shouldGeoreference = ( page == worldFilePageNo );
460 if ( shouldGeoreference )
462 georeferenceOutputPrivate( outputFilePath,
nullptr, bounds, settings.
dpi, shouldGeoreference );
467 double a, b,
c, d, e, f;
468 if ( bounds.isValid() )
473 QFileInfo fi( outputFilePath );
475 QString outputSuffix = fi.suffix();
476 QString worldFileName = fi.absolutePath() +
'/' + fi.completeBaseName() +
'.'
477 + outputSuffix.at( 0 ) + outputSuffix.at( fi.suffix().size() - 1 ) +
'w';
479 writeWorldFile( worldFileName, a, b,
c, d, e, f );
484 captureLabelingResults();
495 int total = iterator->
count();
496 double step = total > 0 ? 100.0 / total : 100.0;
498 while ( iterator->
next() )
503 feedback->setProperty(
"progress", QObject::tr(
"Exporting %1 of %2" ).arg( i + 1 ).arg( total ) );
505 feedback->setProperty(
"progress", QObject::tr(
"Exporting section %1" ).arg( i + 1 ).arg( total ) );
515 QString filePath = iterator->
filePath( baseFilePath, extension );
520 error = QObject::tr(
"Cannot write to %1. This file may be open in another application or may be an invalid path." ).arg( QDir::toNativeSeparators( filePath ) );
540 if ( !mLayout || mLayout->pageCollection()->pageCount() == 0 )
544 if ( settings.
dpi <= 0 )
545 settings.
dpi = mLayout->renderContext().dpi();
547 mErrorFileName.clear();
549 LayoutContextPreviewSettingRestorer restorer( mLayout );
551 LayoutContextSettingsRestorer contextRestorer( mLayout );
552 ( void )contextRestorer;
553 mLayout->renderContext().setDpi( settings.
dpi );
555 mLayout->renderContext().setMaskSettings( createExportMaskSettings() );
559 mLayout->renderContext().setSimplifyMethod( createExportSimplifyMethod() );
562 std::unique_ptr< QgsLayoutGeoPdfExporter > geoPdfExporter;
564 geoPdfExporter = std::make_unique< QgsLayoutGeoPdfExporter >( mLayout );
566 mLayout->renderContext().setFlags( settings.
flags );
579 mLayout->renderContext().setExportThemes( settings.
exportThemes );
591 const QList<QGraphicsItem *> items = mLayout->items( Qt::AscendingOrder );
593 QList< QgsLayoutGeoPdfExporter::ComponentLayerDetail > pdfComponents;
598 QSet<QString> mutuallyExclusiveGroups;
604 component.
name = layerDetail.name;
605 component.
mapLayerId = layerDetail.mapLayerId;
606 component.
opacity = layerDetail.opacity;
608 component.
group = layerDetail.groupName;
609 if ( !layerDetail.mapTheme.isEmpty() )
611 component.
group = layerDetail.mapTheme;
612 mutuallyExclusiveGroups.insert( layerDetail.mapTheme );
615 component.
sourcePdfPath = settings.writeGeoPdf ? geoPdfExporter->generateTemporaryFilepath( QStringLiteral(
"layer_%1.pdf" ).arg( layerId ) ) : baseDir.filePath( QStringLiteral(
"%1_%2.pdf" ).arg( baseFileName ).arg( layerId, 4, 10, QChar(
'0' ) ) );
616 pdfComponents << component;
618 preparePrintAsPdf( mLayout, &printer, component.
sourcePdfPath );
619 preparePrint( mLayout, &printer,
false );
621 if ( !p.begin( &printer ) )
629 return layerExportResult;
631 auto getExportGroupNameFunc = [](
QgsLayoutItem * item )->QString
633 return item->customProperty( QStringLiteral(
"pdfExportGroup" ) ).toString();
635 result = handleLayeredExport( items, exportFunc, getExportGroupNameFunc );
639 if ( settings.writeGeoPdf )
642 details.
dpi = settings.dpi;
644 QgsLayoutSize pageSize = mLayout->pageCollection()->page( 0 )->sizeWithUnits();
649 if ( settings.exportMetadata )
652 details.
author = mLayout->project()->metadata().author();
655 details.
creationDateTime = mLayout->project()->metadata().creationDateTime();
656 details.
subject = mLayout->project()->metadata().abstract();
657 details.
title = mLayout->project()->metadata().title();
658 details.
keywords = mLayout->project()->metadata().keywords();
661 const QList< QgsMapLayer * > layers = mLayout->project()->mapLayers().values();
667 if ( settings.appendGeoreference )
670 QList< QgsLayoutItemMap * > maps;
671 mLayout->layoutItems( maps );
675 georef.
crs = map->crs();
677 const QPointF topLeft = map->mapToScene( QPointF( 0, 0 ) );
678 const QPointF topRight = map->mapToScene( QPointF( map->rect().width(), 0 ) );
679 const QPointF bottomLeft = map->mapToScene( QPointF( 0, map->rect().height() ) );
680 const QPointF bottomRight = map->mapToScene( QPointF( map->rect().width(), map->rect().height() ) );
693 const QTransform t = map->layoutToMapCoordsTransform();
694 const QgsPointXY topLeftMap = t.map( topLeft );
695 const QgsPointXY topRightMap = t.map( topRight );
696 const QgsPointXY bottomLeftMap = t.map( bottomLeft );
697 const QgsPointXY bottomRightMap = t.map( bottomRight );
709 details.
layerOrder = geoPdfExporter->layerOrder();
715 if ( !geoPdfExporter->finalize( pdfComponents, filePath, details ) )
718 mErrorMessage = geoPdfExporter->errorMessage();
728 QPdfWriter printer = QPdfWriter( filePath );
729 preparePrintAsPdf( mLayout, &printer, filePath );
730 preparePrint( mLayout, &printer,
false );
732 if ( !p.begin( &printer ) )
741 bool shouldAppendGeoreference = settings.
appendGeoreference && mLayout && mLayout->referenceMap() && mLayout->referenceMap()->page() == 0;
744 georeferenceOutputPrivate( filePath,
nullptr, QRectF(), settings.
dpi, shouldAppendGeoreference, settings.
exportMetadata );
747 captureLabelingResults();
760 QPdfWriter printer = QPdfWriter( fileName );
763 int total = iterator->
count();
764 double step = total > 0 ? 100.0 / total : 100.0;
767 while ( iterator->
next() )
772 feedback->setProperty(
"progress", QObject::tr(
"Exporting %1 of %2" ).arg( i + 1 ).arg( total ) );
774 feedback->setProperty(
"progress", QObject::tr(
"Exporting section %1" ).arg( i + 1 ) );
786 LayoutContextPreviewSettingRestorer restorer( iterator->
layout() );
788 LayoutContextSettingsRestorer contextRestorer( iterator->
layout() );
789 ( void )contextRestorer;
812 preparePrintAsPdf( iterator->
layout(), &printer, fileName );
813 preparePrint( iterator->
layout(), &printer,
false );
815 if ( !p.begin( &printer ) )
829 error = QObject::tr(
"Cannot write to %1. This file may be open in another application or may be an invalid path." ).arg( QDir::toNativeSeparators( fileName ) );
856 int total = iterator->
count();
857 double step = total > 0 ? 100.0 / total : 100.0;
859 while ( iterator->
next() )
864 feedback->setProperty(
"progress", QObject::tr(
"Exporting %1 of %2" ).arg( i + 1 ).arg( total ) );
866 feedback->setProperty(
"progress", QObject::tr(
"Exporting section %1" ).arg( i + 1 ).arg( total ) );
875 QString filePath = iterator->
filePath( baseFilePath, QStringLiteral(
"pdf" ) );
882 error = QObject::tr(
"Cannot write to %1. This file may be open in another application or may be an invalid path." ).arg( QDir::toNativeSeparators( filePath ) );
900#if defined( HAVE_QTPRINTER )
907 if ( settings.
dpi <= 0 )
908 settings.
dpi = mLayout->renderContext().dpi();
910 mErrorFileName.clear();
912 LayoutContextPreviewSettingRestorer restorer( mLayout );
914 LayoutContextSettingsRestorer contextRestorer( mLayout );
915 ( void )contextRestorer;
916 mLayout->renderContext().setDpi( settings.
dpi );
918 mLayout->renderContext().setFlags( settings.
flags );
925 preparePrint( mLayout, &printer,
true );
927 if ( !p.begin( &printer ) )
936 captureLabelingResults();
947 PrintExportSettings settings = s;
951 int total = iterator->
count();
952 double step = total > 0 ? 100.0 / total : 100.0;
955 while ( iterator->
next() )
960 feedback->setProperty(
"progress", QObject::tr(
"Printing %1 of %2" ).arg( i + 1 ).arg( total ) );
962 feedback->setProperty(
"progress", QObject::tr(
"Printing section %1" ).arg( i + 1 ).arg( total ) );
974 LayoutContextPreviewSettingRestorer restorer( iterator->
layout() );
976 LayoutContextSettingsRestorer contextRestorer( iterator->
layout() );
977 ( void )contextRestorer;
990 preparePrint( iterator->
layout(), &printer,
true );
992 if ( !p.begin( &printer ) )
1002 ExportResult result = exporter.printPrivate( &printer, p, !first, settings.dpi, settings.rasterizeWholeImage );
1006 error = exporter.errorMessage();
1029 if ( settings.
dpi <= 0 )
1030 settings.
dpi = mLayout->renderContext().dpi();
1032 mErrorFileName.clear();
1034 LayoutContextPreviewSettingRestorer restorer( mLayout );
1036 LayoutContextSettingsRestorer contextRestorer( mLayout );
1037 ( void )contextRestorer;
1038 mLayout->renderContext().setDpi( settings.
dpi );
1040 mLayout->renderContext().setFlags( settings.
flags );
1044 mLayout->renderContext().setMaskSettings( createExportMaskSettings() );
1048 mLayout->renderContext().setSimplifyMethod( createExportSimplifyMethod() );
1051 QFileInfo fi( filePath );
1054 pageDetails.
baseName = fi.baseName();
1055 pageDetails.
extension = fi.completeSuffix();
1059 for (
int i = 0; i < mLayout->pageCollection()->pageCount(); ++i )
1061 if ( !mLayout->pageCollection()->shouldExportPage( i ) )
1066 pageDetails.
page = i;
1073 if ( mLayout->pageCollection()->pageCount() == 1 )
1076 bounds = mLayout->layoutBounds(
true );
1081 bounds = mLayout->pageItemBounds( i,
true );
1090 bounds = QRectF( pageItem->pos().x(), pageItem->pos().y(), pageItem->rect().width(), pageItem->rect().height() );
1094 int width =
static_cast< int >( bounds.width() * settings.
dpi / inchesToLayoutUnits );
1096 int height =
static_cast< int >( bounds.height() * settings.
dpi / inchesToLayoutUnits );
1097 if ( width == 0 || height == 0 )
1106 const QRectF paperRect = QRectF( pageItem->pos().x(),
1107 pageItem->pos().y(),
1108 pageItem->rect().width(),
1109 pageItem->rect().height() );
1111 QDomNode svgDocRoot;
1112 const QList<QGraphicsItem *> items = mLayout->items( paperRect,
1113 Qt::IntersectsItemBoundingRect,
1114 Qt::AscendingOrder );
1118 return renderToLayeredSvg( settings, width, height, i, bounds, fileName, layerId, layerDetail.name, svg, svgDocRoot, settings.
exportMetadata );
1120 auto getExportGroupNameFunc = [](
QgsLayoutItem * )->QString
1124 ExportResult res = handleLayeredExport( items, exportFunc, getExportGroupNameFunc );
1129 appendMetadataToSvg( svg );
1131 QFile out( fileName );
1132 bool openOk = out.open( QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate );
1135 mErrorFileName = fileName;
1139 out.write( svg.toByteArray() );
1145 QSvgGenerator generator;
1148 generator.setTitle( mLayout->project()->metadata().title() );
1149 generator.setDescription( mLayout->project()->metadata().abstract() );
1151 generator.setOutputDevice( &svgBuffer );
1152 generator.setSize( QSize( width, height ) );
1153 generator.setViewBox( QRect( 0, 0, width, height ) );
1154 generator.setResolution(
static_cast< int >( std::round( settings.
dpi ) ) );
1157 bool createOk = p.begin( &generator );
1160 mErrorFileName = fileName;
1173 svgBuffer.open( QIODevice::ReadOnly );
1177 if ( ! svg.setContent( &svgBuffer,
false, &errorMsg, &errorLine ) )
1179 mErrorFileName = fileName;
1184 appendMetadataToSvg( svg );
1186 QFile out( fileName );
1187 bool openOk = out.open( QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate );
1190 mErrorFileName = fileName;
1194 out.write( svg.toByteArray() );
1198 captureLabelingResults();
1209 int total = iterator->
count();
1210 double step = total > 0 ? 100.0 / total : 100.0;
1212 while ( iterator->
next() )
1217 feedback->setProperty(
"progress", QObject::tr(
"Exporting %1 of %2" ).arg( i + 1 ).arg( total ) );
1219 feedback->setProperty(
"progress", QObject::tr(
"Exporting section %1" ).arg( i + 1 ).arg( total ) );
1229 QString filePath = iterator->
filePath( baseFilePath, QStringLiteral(
"svg" ) );
1236 error = QObject::tr(
"Cannot write to %1. This file may be open in another application or may be an invalid path." ).arg( QDir::toNativeSeparators( filePath ) );
1257 return mLabelingResults;
1262 QMap<QString, QgsLabelingResults *> res;
1263 std::swap( mLabelingResults, res );
1267void QgsLayoutExporter::preparePrintAsPdf(
QgsLayout *layout, QPagedPaintDevice *device,
const QString &filePath )
1269 QFileInfo fi( filePath );
1271 if ( !dir.exists( fi.absolutePath() ) )
1273 dir.mkpath( fi.absolutePath() );
1276 updatePrinterPageSize(
layout, device, firstPageToBeExported(
layout ) );
1282#if defined(HAS_KDE_QT5_PDF_TRANSFORM_FIX) || QT_VERSION >= QT_VERSION_CHECK(6, 3, 0)
1289void QgsLayoutExporter::preparePrint(
QgsLayout *layout, QPagedPaintDevice *device,
bool setFirstPageSize )
1291 if ( QPdfWriter *pdf =
dynamic_cast<QPdfWriter *
>( device ) )
1295#if defined( HAVE_QTPRINTER )
1296 else if ( QPrinter *printer =
dynamic_cast<QPrinter *
>( device ) )
1298 printer->setFullPage(
true );
1299 printer->setColorMode( QPrinter::Color );
1305 if ( setFirstPageSize )
1307 updatePrinterPageSize(
layout, device, firstPageToBeExported(
layout ) );
1313 if ( mLayout->pageCollection()->pageCount() == 0 )
1316 preparePrint( mLayout, device,
true );
1318 if ( !p.begin( device ) )
1324 printPrivate( device, p );
1329QgsLayoutExporter::ExportResult QgsLayoutExporter::printPrivate( QPagedPaintDevice *device, QPainter &painter,
bool startNewPage,
double dpi,
bool rasterize )
1333 int toPage = mLayout->pageCollection()->pageCount() - 1;
1335#if defined( HAVE_QTPRINTER )
1336 if ( QPrinter *printer =
dynamic_cast<QPrinter *
>( device ) )
1338 if ( printer->fromPage() >= 1 )
1339 fromPage = printer->fromPage() - 1;
1340 if ( printer->toPage() >= 1 )
1341 toPage = printer->toPage() - 1;
1345 bool pageExported =
false;
1348 for (
int i = fromPage; i <= toPage; ++i )
1350 if ( !mLayout->pageCollection()->shouldExportPage( i ) )
1355 updatePrinterPageSize( mLayout, device, i );
1356 if ( ( pageExported && i > fromPage ) || startNewPage )
1362 if ( !image.isNull() )
1364 QRectF targetArea( 0, 0, image.width(), image.height() );
1365 painter.drawImage( targetArea, image, targetArea );
1371 pageExported =
true;
1376 for (
int i = fromPage; i <= toPage; ++i )
1378 if ( !mLayout->pageCollection()->shouldExportPage( i ) )
1383 updatePrinterPageSize( mLayout, device, i );
1385 if ( ( pageExported && i > fromPage ) || startNewPage )
1390 pageExported =
true;
1396void QgsLayoutExporter::updatePrinterPageSize(
QgsLayout *layout, QPagedPaintDevice *device,
int page )
1401 QPageLayout pageLayout( QPageSize( pageSizeMM.
toQSizeF(), QPageSize::Millimeter ),
1402 QPageLayout::Portrait,
1403 QMarginsF( 0, 0, 0, 0 ) );
1404 pageLayout.setMode( QPageLayout::FullPageMode );
1405 device->setPageLayout( pageLayout );
1406 device->setPageMargins( QMarginsF( 0, 0, 0, 0 ) );
1408#if defined( HAVE_QTPRINTER )
1409 if ( QPrinter *printer =
dynamic_cast<QPrinter *
>( device ) )
1411 printer->setFullPage(
true );
1416QgsLayoutExporter::ExportResult QgsLayoutExporter::renderToLayeredSvg(
const SvgExportSettings &settings,
double width,
double height,
int page,
const QRectF &bounds,
const QString &filename,
unsigned int svgLayerId,
const QString &layerName, QDomDocument &svg, QDomNode &svgDocRoot,
bool includeMetadata )
const
1420 QSvgGenerator generator;
1421 if ( includeMetadata )
1424 generator.setTitle( l->name() );
1425 else if ( mLayout->project() )
1426 generator.setTitle( mLayout->project()->title() );
1429 generator.setOutputDevice( &svgBuffer );
1430 generator.setSize( QSize(
static_cast< int >( std::round( width ) ),
1431 static_cast< int >( std::round( height ) ) ) );
1432 generator.setViewBox( QRect( 0, 0,
1433 static_cast< int >( std::round( width ) ),
1434 static_cast< int >( std::round( height ) ) ) );
1435 generator.setResolution(
static_cast< int >( std::round( settings.dpi ) ) );
1437 QPainter svgPainter( &generator );
1438 if ( settings.cropToContents )
1449 svgBuffer.open( QIODevice::ReadOnly );
1453 if ( ! doc.setContent( &svgBuffer,
false, &errorMsg, &errorLine ) )
1455 mErrorFileName = filename;
1458 if ( 1 == svgLayerId )
1460 svg = QDomDocument( doc.doctype() );
1461 svg.appendChild( svg.importNode( doc.firstChild(),
false ) );
1462 svgDocRoot = svg.importNode( doc.elementsByTagName( QStringLiteral(
"svg" ) ).at( 0 ),
false );
1463 svgDocRoot.toElement().setAttribute( QStringLiteral(
"xmlns:inkscape" ), QStringLiteral(
"http://www.inkscape.org/namespaces/inkscape" ) );
1464 svg.appendChild( svgDocRoot );
1466 QDomNode mainGroup = svg.importNode( doc.elementsByTagName( QStringLiteral(
"g" ) ).at( 0 ),
true );
1467 mainGroup.toElement().setAttribute( QStringLiteral(
"id" ), layerName );
1468 mainGroup.toElement().setAttribute( QStringLiteral(
"inkscape:label" ), layerName );
1469 mainGroup.toElement().setAttribute( QStringLiteral(
"inkscape:groupmode" ), QStringLiteral(
"layer" ) );
1470 QDomNode defs = svg.importNode( doc.elementsByTagName( QStringLiteral(
"defs" ) ).at( 0 ),
true );
1471 svgDocRoot.appendChild( defs );
1472 svgDocRoot.appendChild( mainGroup );
1477void QgsLayoutExporter::appendMetadataToSvg( QDomDocument &svg )
const
1480 QDomElement metadataElement = svg.createElement( QStringLiteral(
"metadata" ) );
1481 QDomElement rdfElement = svg.createElement( QStringLiteral(
"rdf:RDF" ) );
1482 rdfElement.setAttribute( QStringLiteral(
"xmlns:rdf" ), QStringLiteral(
"http://www.w3.org/1999/02/22-rdf-syntax-ns#" ) );
1483 rdfElement.setAttribute( QStringLiteral(
"xmlns:rdfs" ), QStringLiteral(
"http://www.w3.org/2000/01/rdf-schema#" ) );
1484 rdfElement.setAttribute( QStringLiteral(
"xmlns:dc" ), QStringLiteral(
"http://purl.org/dc/elements/1.1/" ) );
1485 QDomElement descriptionElement = svg.createElement( QStringLiteral(
"rdf:Description" ) );
1486 QDomElement workElement = svg.createElement( QStringLiteral(
"cc:Work" ) );
1487 workElement.setAttribute( QStringLiteral(
"rdf:about" ), QString() );
1489 auto addTextNode = [&workElement, &descriptionElement, &svg](
const QString & tag,
const QString & value )
1492 QDomElement element = svg.createElement( tag );
1493 QDomText t = svg.createTextNode( value );
1494 element.appendChild( t );
1495 workElement.appendChild( element );
1498 descriptionElement.setAttribute( tag, value );
1501 addTextNode( QStringLiteral(
"dc:format" ), QStringLiteral(
"image/svg+xml" ) );
1502 addTextNode( QStringLiteral(
"dc:title" ), metadata.
title() );
1503 addTextNode( QStringLiteral(
"dc:date" ), metadata.
creationDateTime().toString( Qt::ISODate ) );
1504 addTextNode( QStringLiteral(
"dc:identifier" ), metadata.
identifier() );
1505 addTextNode( QStringLiteral(
"dc:description" ), metadata.
abstract() );
1507 auto addAgentNode = [&workElement, &descriptionElement, &svg](
const QString & tag,
const QString & value )
1510 QDomElement inkscapeElement = svg.createElement( tag );
1511 QDomElement agentElement = svg.createElement( QStringLiteral(
"cc:Agent" ) );
1512 QDomElement titleElement = svg.createElement( QStringLiteral(
"dc:title" ) );
1513 QDomText t = svg.createTextNode( value );
1514 titleElement.appendChild( t );
1515 agentElement.appendChild( titleElement );
1516 inkscapeElement.appendChild( agentElement );
1517 workElement.appendChild( inkscapeElement );
1520 QDomElement bagElement = svg.createElement( QStringLiteral(
"rdf:Bag" ) );
1521 QDomElement liElement = svg.createElement( QStringLiteral(
"rdf:li" ) );
1522 t = svg.createTextNode( value );
1523 liElement.appendChild( t );
1524 bagElement.appendChild( liElement );
1526 QDomElement element = svg.createElement( tag );
1527 element.appendChild( bagElement );
1528 descriptionElement.appendChild( element );
1531 addAgentNode( QStringLiteral(
"dc:creator" ), metadata.
author() );
1532 addAgentNode( QStringLiteral(
"dc:publisher" ), QStringLiteral(
"QGIS %1" ).arg(
Qgis::version() ) );
1536 QDomElement element = svg.createElement( QStringLiteral(
"dc:subject" ) );
1537 QDomElement bagElement = svg.createElement( QStringLiteral(
"rdf:Bag" ) );
1539 for (
auto it = keywords.constBegin(); it != keywords.constEnd(); ++it )
1541 const QStringList words = it.value();
1542 for (
const QString &keyword : words )
1544 QDomElement liElement = svg.createElement( QStringLiteral(
"rdf:li" ) );
1545 QDomText t = svg.createTextNode( keyword );
1546 liElement.appendChild( t );
1547 bagElement.appendChild( liElement );
1550 element.appendChild( bagElement );
1551 workElement.appendChild( element );
1552 descriptionElement.appendChild( element );
1555 rdfElement.appendChild( descriptionElement );
1556 rdfElement.appendChild( workElement );
1557 metadataElement.appendChild( rdfElement );
1558 svg.documentElement().appendChild( metadataElement );
1559 svg.documentElement().setAttribute( QStringLiteral(
"xmlns:cc" ), QStringLiteral(
"http://creativecommons.org/ns#" ) );
1562std::unique_ptr<double[]> QgsLayoutExporter::computeGeoTransform(
const QgsLayoutItemMap *map,
const QRectF ®ion,
double dpi )
const
1565 map = mLayout->referenceMap();
1571 dpi = mLayout->renderContext().dpi();
1574 QRectF exportRegion = region;
1575 if ( !exportRegion.isValid() )
1577 int pageNumber = map->
page();
1580 double pageY = page->pos().y();
1581 QSizeF pageSize = page->rect().size();
1582 exportRegion = QRectF( 0, pageY, pageSize.width(), pageSize.height() );
1586 QRectF mapItemSceneRect = map->mapRectToScene( map->rect() );
1589 double outputHeightMM = exportRegion.height();
1590 double outputWidthMM = exportRegion.width();
1594 double mapXCenter = mapExtent.
center().
x();
1595 double mapYCenter = mapExtent.
center().
y();
1597 double sinAlpha = std::sin( alpha );
1598 double cosAlpha = std::cos( alpha );
1601 QPointF mapItemPos = map->pos();
1603 mapItemPos.rx() -= exportRegion.left();
1604 mapItemPos.ry() -= exportRegion.top();
1607 double xRatio = mapExtent.
width() / mapItemSceneRect.width();
1608 double yRatio = mapExtent.
height() / mapItemSceneRect.height();
1609 double xmin = mapExtent.
xMinimum() - mapItemPos.x() * xRatio;
1610 double ymax = mapExtent.
yMaximum() + mapItemPos.y() * yRatio;
1611 QgsRectangle paperExtent( xmin, ymax - outputHeightMM * yRatio, xmin + outputWidthMM * xRatio, ymax );
1614 double X0 = paperExtent.xMinimum();
1615 double Y0 = paperExtent.yMaximum();
1620 double X1 = X0 - mapXCenter;
1621 double Y1 = Y0 - mapYCenter;
1622 double X2 = X1 * cosAlpha + Y1 * sinAlpha;
1623 double Y2 = -X1 * sinAlpha + Y1 * cosAlpha;
1624 X0 = X2 + mapXCenter;
1625 Y0 = Y2 + mapYCenter;
1629 int pageWidthPixels =
static_cast< int >( dpi * outputWidthMM / 25.4 );
1630 int pageHeightPixels =
static_cast< int >( dpi * outputHeightMM / 25.4 );
1631 double pixelWidthScale = paperExtent.width() / pageWidthPixels;
1632 double pixelHeightScale = paperExtent.height() / pageHeightPixels;
1635 std::unique_ptr<double[]> t(
new double[6] );
1637 t[1] = cosAlpha * pixelWidthScale;
1638 t[2] = -sinAlpha * pixelWidthScale;
1640 t[4] = -sinAlpha * pixelHeightScale;
1641 t[5] = -cosAlpha * pixelHeightScale;
1646void QgsLayoutExporter::writeWorldFile(
const QString &worldFileName,
double a,
double b,
double c,
double d,
double e,
double f )
const
1648 QFile worldFile( worldFileName );
1649 if ( !worldFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
1653 QTextStream fout( &worldFile );
1657 fout << QString::number( a,
'f', 12 ) <<
"\r\n";
1658 fout << QString::number( d,
'f', 12 ) <<
"\r\n";
1659 fout << QString::number( b,
'f', 12 ) <<
"\r\n";
1660 fout << QString::number( e,
'f', 12 ) <<
"\r\n";
1661 fout << QString::number(
c,
'f', 12 ) <<
"\r\n";
1662 fout << QString::number( f,
'f', 12 ) <<
"\r\n";
1667 return georeferenceOutputPrivate( file, map, exportRegion, dpi,
false );
1670bool QgsLayoutExporter::georeferenceOutputPrivate(
const QString &file,
QgsLayoutItemMap *map,
const QRectF &exportRegion,
double dpi,
bool includeGeoreference,
bool includeMetadata )
const
1675 if ( !map && includeGeoreference )
1676 map = mLayout->referenceMap();
1678 std::unique_ptr<double[]> t;
1680 if ( map && includeGeoreference )
1683 dpi = mLayout->renderContext().dpi();
1685 t = computeGeoTransform( map, exportRegion, dpi );
1690 CPLSetConfigOption(
"GDAL_PDF_DPI", QString::number( dpi ).toUtf8().constData() );
1695 GDALSetGeoTransform( outputDS.get(), t.get() );
1697 if ( includeMetadata )
1699 QString creationDateString;
1700 const QDateTime creationDateTime = mLayout->project()->metadata().creationDateTime();
1701 if ( creationDateTime.isValid() )
1703 creationDateString = QStringLiteral(
"D:%1" ).arg( mLayout->project()->metadata().creationDateTime().toString( QStringLiteral(
"yyyyMMddHHmmss" ) ) );
1704 if ( creationDateTime.timeZone().isValid() )
1706 int offsetFromUtc = creationDateTime.timeZone().offsetFromUtc( creationDateTime );
1707 creationDateString += ( offsetFromUtc >= 0 ) ?
'+' :
'-';
1708 offsetFromUtc = std::abs( offsetFromUtc );
1709 int offsetHours = offsetFromUtc / 3600;
1710 int offsetMins = ( offsetFromUtc % 3600 ) / 60;
1711 creationDateString += QStringLiteral(
"%1'%2'" ).arg( offsetHours ).arg( offsetMins );
1714 GDALSetMetadataItem( outputDS.get(),
"CREATION_DATE", creationDateString.toUtf8().constData(),
nullptr );
1716 GDALSetMetadataItem( outputDS.get(),
"AUTHOR", mLayout->project()->metadata().author().toUtf8().constData(),
nullptr );
1717 const QString creator = QStringLiteral(
"QGIS %1" ).arg(
Qgis::version() );
1718 GDALSetMetadataItem( outputDS.get(),
"CREATOR", creator.toUtf8().constData(),
nullptr );
1719 GDALSetMetadataItem( outputDS.get(),
"PRODUCER", creator.toUtf8().constData(),
nullptr );
1720 GDALSetMetadataItem( outputDS.get(),
"SUBJECT", mLayout->project()->metadata().abstract().toUtf8().constData(),
nullptr );
1721 GDALSetMetadataItem( outputDS.get(),
"TITLE", mLayout->project()->metadata().title().toUtf8().constData(),
nullptr );
1724 QStringList allKeywords;
1725 for (
auto it = keywords.constBegin(); it != keywords.constEnd(); ++it )
1727 allKeywords.append( QStringLiteral(
"%1: %2" ).arg( it.key(), it.value().join(
',' ) ) );
1729 const QString keywordString = allKeywords.join(
';' );
1730 GDALSetMetadataItem( outputDS.get(),
"KEYWORDS", keywordString.toUtf8().constData(),
nullptr );
1736 CPLSetConfigOption(
"GDAL_PDF_DPI",
nullptr );
1743 if ( items.count() == 1 )
1747 QString name = layoutItem->displayName();
1749 if ( name.startsWith(
'<' ) && name.endsWith(
'>' ) )
1750 name = name.mid( 1, name.length() - 2 );
1754 else if ( items.count() > 1 )
1756 QStringList currentLayerItemTypes;
1757 for ( QGraphicsItem *item : items )
1763 if ( !currentLayerItemTypes.contains( itemType ) && !currentLayerItemTypes.contains( itemTypePlural ) )
1764 currentLayerItemTypes << itemType;
1765 else if ( currentLayerItemTypes.contains( itemType ) )
1767 currentLayerItemTypes.replace( currentLayerItemTypes.indexOf( itemType ), itemTypePlural );
1772 if ( !currentLayerItemTypes.contains( QObject::tr(
"Other" ) ) )
1773 currentLayerItemTypes.append( QObject::tr(
"Other" ) );
1776 return currentLayerItemTypes.join( QLatin1String(
", " ) );
1778 return QObject::tr(
"Layer %1" ).arg( layerId );
1783 const std::function<QString(
QgsLayoutItem *item )> &getItemExportGroupFunc )
1785 LayoutItemHider itemHider( items );
1790 QString previousItemGroup;
1791 unsigned int layerId = 1;
1793 itemHider.hideAll();
1794 const QList< QGraphicsItem * > itemsToIterate = itemHider.itemsToIterate();
1795 QList< QGraphicsItem * > currentLayerItems;
1796 for ( QGraphicsItem *item : itemsToIterate )
1800 bool canPlaceInExistingLayer =
false;
1801 QString thisItemExportGroupName;
1805 thisItemExportGroupName = getItemExportGroupFunc( layoutItem );
1806 if ( !thisItemExportGroupName.isEmpty() )
1808 if ( thisItemExportGroupName != previousItemGroup && !currentLayerItems.empty() )
1811 layerDetails.
groupName = thisItemExportGroupName;
1814 switch ( itemExportBehavior )
1818 switch ( prevItemBehavior )
1821 canPlaceInExistingLayer =
true;
1825 canPlaceInExistingLayer = prevType == -1 || prevType == layoutItem->
type();
1830 canPlaceInExistingLayer =
false;
1838 switch ( prevItemBehavior )
1842 canPlaceInExistingLayer = prevType == -1 || prevType == layoutItem->
type();
1847 canPlaceInExistingLayer =
false;
1855 canPlaceInExistingLayer =
false;
1860 canPlaceInExistingLayer =
false;
1863 prevItemBehavior = itemExportBehavior;
1864 prevType = layoutItem->
type();
1865 previousItemGroup = thisItemExportGroupName;
1870 previousItemGroup.clear();
1873 if ( canPlaceInExistingLayer )
1875 currentLayerItems << item;
1880 if ( !currentLayerItems.isEmpty() )
1884 ExportResult result = exportFunc( layerId, layerDetails );
1888 currentLayerItems.clear();
1891 itemHider.hideAll();
1896 int layoutItemLayerIdx = 0;
1898 mLayout->renderContext().setCurrentExportLayer( layoutItemLayerIdx );
1904 mLayout->renderContext().setCurrentExportLayer( layoutItemLayerIdx );
1908 ExportResult result = exportFunc( layerId, layerDetails );
1913 layoutItemLayerIdx++;
1915 layerDetails.mapLayerId.clear();
1917 mLayout->renderContext().setCurrentExportLayer( -1 );
1920 currentLayerItems.clear();
1924 currentLayerItems << item;
1926 layerDetails.groupName = thisItemExportGroupName;
1929 if ( !currentLayerItems.isEmpty() )
1932 ExportResult result = exportFunc( layerId, layerDetails );
1947 return simplifyMethod;
1970 int pageNumber = map->
page();
1972 double pageY = page->pos().y();
1973 QSizeF pageSize = page->rect().size();
1974 QRectF pageRect( 0, pageY, pageSize.width(), pageSize.height() );
1990 double destinationHeight = exportRegion.height();
1991 double destinationWidth = exportRegion.width();
1993 QRectF mapItemSceneRect = map->mapRectToScene( map->rect() );
1998 double xRatio = mapExtent.
width() / mapItemSceneRect.width();
1999 double yRatio = mapExtent.
height() / mapItemSceneRect.height();
2001 double xCenter = mapExtent.
center().
x();
2002 double yCenter = mapExtent.
center().
y();
2005 QPointF mapItemPos = map->pos();
2007 mapItemPos.rx() -= exportRegion.left();
2008 mapItemPos.ry() -= exportRegion.top();
2010 double xmin = mapExtent.
xMinimum() - mapItemPos.x() * xRatio;
2011 double ymax = mapExtent.
yMaximum() + mapItemPos.y() * yRatio;
2012 QgsRectangle paperExtent( xmin, ymax - destinationHeight * yRatio, xmin + destinationWidth * xRatio, ymax );
2014 double X0 = paperExtent.
xMinimum();
2015 double Y0 = paperExtent.
yMinimum();
2018 dpi = mLayout->renderContext().dpi();
2020 int widthPx =
static_cast< int >( dpi * destinationWidth / 25.4 );
2021 int heightPx =
static_cast< int >( dpi * destinationHeight / 25.4 );
2023 double Ww = paperExtent.
width() / widthPx;
2024 double Hh = paperExtent.
height() / heightPx;
2033 s[5] = Y0 + paperExtent.
height();
2037 r[0] = std::cos( alpha );
2038 r[1] = -std::sin( alpha );
2039 r[2] = xCenter * ( 1 - std::cos( alpha ) ) + yCenter * std::sin( alpha );
2040 r[3] = std::sin( alpha );
2041 r[4] = std::cos( alpha );
2042 r[5] = - xCenter * std::sin( alpha ) + yCenter * ( 1 - std::cos( alpha ) );
2045 a = r[0] * s[0] + r[1] * s[3];
2046 b = r[0] * s[1] + r[1] * s[4];
2047 c = r[0] * s[2] + r[1] * s[5] + r[2];
2048 d = r[3] * s[0] + r[4] * s[3];
2049 e = r[3] * s[1] + r[4] * s[4];
2050 f = r[3] * s[2] + r[4] * s[5] + r[5];
2058 QList< QgsLayoutItem *> items;
2064 if ( currentItem->isVisible() && currentItem->requiresRasterization() )
2075 QList< QgsLayoutItem *> items;
2081 if ( currentItem->isVisible() && currentItem->containsAdvancedEffects() )
2094 if ( mLayout->pageCollection()->pageCount() == 1 )
2097 bounds = mLayout->layoutBounds(
true );
2102 bounds = mLayout->pageItemBounds( page,
true );
2104 if ( bounds.width() <= 0 || bounds.height() <= 0 )
2112 bounds = bounds.adjusted( -settings.
cropMargins.
left() * pixelToLayoutUnits,
2124int QgsLayoutExporter::firstPageToBeExported(
QgsLayout *layout )
2127 for (
int i = 0; i < pageCount; ++i )
2141 if ( details.
page == 0 )
2151void QgsLayoutExporter::captureLabelingResults()
2153 qDeleteAll( mLabelingResults );
2154 mLabelingResults.clear();
2156 QList< QgsLayoutItemMap * > maps;
2157 mLayout->layoutItems( maps );
2161 mLabelingResults[ map->
uuid() ] = map->mExportLabelingResults.release();
2165bool QgsLayoutExporter::saveImage(
const QImage &image,
const QString &imageFilename,
const QString &imageFormat,
QgsProject *projectForMetadata )
2167 QImageWriter w( imageFilename, imageFormat.toLocal8Bit().constData() );
2168 if ( imageFormat.compare( QLatin1String(
"tiff" ), Qt::CaseInsensitive ) == 0 || imageFormat.compare( QLatin1String(
"tif" ), Qt::CaseInsensitive ) == 0 )
2170 w.setCompression( 1 );
2172 if ( projectForMetadata )
2174 w.setText( QStringLiteral(
"Author" ), projectForMetadata->
metadata().
author() );
2175 const QString creator = QStringLiteral(
"QGIS %1" ).arg(
Qgis::version() );
2176 w.setText( QStringLiteral(
"Creator" ), creator );
2177 w.setText( QStringLiteral(
"Producer" ), creator );
2178 w.setText( QStringLiteral(
"Subject" ), projectForMetadata->
metadata().
abstract() );
2179 w.setText( QStringLiteral(
"Created" ), projectForMetadata->
metadata().
creationDateTime().toString( Qt::ISODate ) );
2180 w.setText( QStringLiteral(
"Title" ), projectForMetadata->
metadata().
title() );
2183 QStringList allKeywords;
2184 for (
auto it = keywords.constBegin(); it != keywords.constEnd(); ++it )
2186 allKeywords.append( QStringLiteral(
"%1: %2" ).arg( it.key(), it.value().join(
',' ) ) );
2188 const QString keywordString = allKeywords.join(
';' );
2189 w.setText( QStringLiteral(
"Keywords" ), keywordString );
2191 return w.write( image );
static QString version()
Version string.
@ Millimeters
Millimeters.
@ GeometrySimplification
The geometries can be simplified using the current map2pixel context state.
@ SnappedToGridGlobal
Snap to a global grid based on the tolerance. Good for consistent results for incoming vertices,...
@ Warning
Warning message.
TextRenderFormat
Options for rendering text.
@ AlwaysOutlines
Always render text using path objects (AKA outlines/curves). This setting guarantees the best quality...
@ PreferredGdal
Preferred format for conversion of CRS to WKT for use with the GDAL library.
An abstract base class for QgsLayout based classes which can be exported by QgsLayoutExporter.
virtual bool endRender()=0
Ends the render, performing any required cleanup tasks.
virtual QgsLayout * layout()=0
Returns the layout associated with the iterator.
virtual bool next()=0
Iterates to next feature, returning false if no more features exist to iterate over.
virtual bool beginRender()=0
Called when rendering begins, before iteration commences.
virtual QString filePath(const QString &baseFilePath, const QString &extension)=0
Returns the file path for the current feature, based on a specified base file path and extension.
virtual int count() const =0
Returns the number of features to iterate over.
static QgsLayoutItemRegistry * layoutItemRegistry()
Returns the application's layout item registry, used for layout item types.
QString toWkt(Qgis::CrsWktVariant variant=Qgis::CrsWktVariant::Wkt1Gdal, bool multiline=false, int indentationWidth=4) const
Returns a WKT representation of this CRS.
Base class for feedback objects to be used for cancellation of something running in a worker thread.
bool isCanceled() const
Tells whether the operation has been canceled already.
void setProgress(double progress)
Sets the current progress for the feedback object.
Handles rendering and exports of layouts to various formats.
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.
virtual ~QgsLayoutExporter()
QImage renderRegionToImage(const QRectF ®ion, QSize imageSize=QSize(), double dpi=-1) const
Renders a region of the layout to an image.
QMap< QString, QgsLabelingResults * > takeLabelingResults()
Takes the labeling results for all map items included in the export.
static bool requiresRasterization(const QgsLayout *layout)
Returns true if the specified layout contains visible items which have settings that require rasteriz...
QgsLayout * layout() const
Returns the layout linked to this exporter.
bool georeferenceOutput(const QString &file, QgsLayoutItemMap *referenceMap=nullptr, const QRectF &exportRegion=QRectF(), double dpi=-1) const
Georeferences a file (image of PDF) exported from the layout.
static const QgsSettingsEntryBool * settingOpenAfterExportingPdf
Settings entry - Whether to automatically open pdfs after exporting them.
virtual QString generateFileName(const PageExportDetails &details) const
Generates the file name for a page during export.
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.
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.
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.
void computeWorldFileParameters(double &a, double &b, double &c, double &d, double &e, double &f, double dpi=-1) const
Compute world file parameters.
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.
QMap< QString, QgsLabelingResults * > labelingResults()
Returns the labeling results for all map items included in the export.
static bool containsAdvancedEffects(const QgsLayout *layout)
Returns true if the specified layout contains visible items which have settings such as opacity which...
void renderRegion(QPainter *painter, const QRectF ®ion) const
Renders a region from the layout to a painter.
Contains the configuration for a single snap guide used by a layout.
Layout graphical items for displaying a map.
double mapRotation(QgsLayoutObject::PropertyValueType valueType=QgsLayoutObject::EvaluatedValue) const
Returns the rotation used for drawing the map within the layout item, in degrees clockwise.
QgsRectangle extent() const
Returns the current map extent.
QgsCoordinateReferenceSystem crs() const
Returns coordinate reference system used for rendering the map.
Item representing the paper in a layout.
QgsLayoutItemAbstractMetadata * itemMetadata(int type) const
Returns the metadata for the specified item type.
Base class for graphical items within a QgsLayout.
QgsLayoutSize sizeWithUnits() const
Returns the item's current size, including units.
virtual QgsLayoutItem::ExportLayerDetail exportLayerDetails() const
Returns the details for the specified current export layer.
virtual bool nextExportPart()
Moves to the next export part for a multi-layered export item, during a multi-layered export.
virtual void startLayeredExport()
Starts a multi-layer export operation.
int page() const
Returns the page the item is currently on, with the first page returning 0.
int type() const override
Returns a unique graphics item type identifier.
virtual void stopLayeredExport()
Stops a multi-layer export operation.
virtual QString uuid() const
Returns the item identification string.
ExportLayerBehavior
Behavior of item when exporting to layered outputs.
@ ItemContainsSubLayers
Item contains multiple sublayers which must be individually exported.
@ MustPlaceInOwnLayer
Item must be placed in its own individual layer.
@ CanGroupWithItemsOfSameType
Item can only be placed on layers with other items of the same type, but multiple items of this type ...
@ CanGroupWithAnyOtherItem
Item can be placed on a layer with any other item (default behavior)
virtual ExportLayerBehavior exportLayerBehavior() const
Returns the behavior of this item during exporting to layered exports (e.g.
QgsLayoutMeasurement convert(QgsLayoutMeasurement measurement, Qgis::LayoutUnit targetUnits) const
Converts a measurement from one unit to another.
This class provides a method of storing measurements for use in QGIS layouts using a variety of diffe...
int pageCount() const
Returns the number of pages in the collection.
bool shouldExportPage(int page) const
Returns whether the specified page number should be included in exports of the layouts.
QgsLayoutItemPage * page(int pageNumber)
Returns a specific page (by pageNumber) from the collection.
This class provides a method of storing points, consisting of an x and y coordinate,...
double x() const
Returns x coordinate of point.
double y() const
Returns y coordinate of point.
void setDpi(double dpi)
Sets the dpi for outputting the layout.
void setSimplifyMethod(const QgsVectorSimplifyMethod &method)
Sets the simplification setting to use when rendering vector layers.
void setTextRenderFormat(Qgis::TextRenderFormat format)
Sets the text render format, which dictates how text is rendered (e.g.
QgsLayoutRenderContext::Flags flags() const
Returns the current combination of flags used for rendering the layout.
void setFlag(QgsLayoutRenderContext::Flag flag, bool on=true)
Enables or disables a particular rendering flag for the layout.
double dpi() const
Returns the dpi for outputting the layout.
@ FlagRenderLabelsByMapLayer
When rendering map items to multi-layered exports, render labels belonging to different layers into s...
@ FlagUseAdvancedEffects
Enable advanced effects such as blend modes.
@ FlagLosslessImageRendering
Render images losslessly whenever possible, instead of the default lossy jpeg rendering used for some...
@ FlagAntialiasing
Use antialiasing when drawing items.
@ FlagSynchronousLegendGraphics
Query legend graphics synchronously.
@ FlagForceVectorOutput
Force output in vector format where possible, even if items require rasterization to keep their corre...
void setPredefinedScales(const QVector< qreal > &scales)
Sets the list of predefined scales to use with the layout.
void setMaskSettings(const QgsMaskRenderSettings &settings)
Sets the mask render settings, which control how masks are drawn and behave during map renders.
void setFlags(QgsLayoutRenderContext::Flags flags)
Sets the combination of flags that will be used for rendering the layout.
const QgsLayoutMeasurementConverter & measurementConverter() const
Returns the layout measurement converter to be used in the layout.
This class provides a method of storing sizes, consisting of a width and height, for use in QGIS layo...
QSizeF toQSizeF() const
Converts the layout size to a QSizeF.
Base class for layouts, which can contain items such as maps, labels, scalebars, etc.
QgsLayoutRenderContext & renderContext()
Returns a reference to the layout's render context, which stores information relating to the current ...
QgsLayoutPageCollection * pageCollection()
Returns a pointer to the layout's page collection, which stores and manages page items in the layout.
void layoutItems(QList< T * > &itemList) const
Returns a list of layout items of a specific type.
Line string geometry type, with support for z-dimension and m-values.
Base class for all map layer types.
double top() const
Returns the top margin.
double right() const
Returns the right margin.
double bottom() const
Returns the bottom margin.
double left() const
Returns the left margin.
Contains settings regarding how masks are calculated and handled during a map render.
void setSimplificationTolerance(double tolerance)
Sets a simplification tolerance (in painter units) to use for on-the-fly simplification of mask paths...
Interface for master layout type objects, such as print layouts and reports.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true)
Adds a message to the log instance (and creates it if necessary).
static void fixEngineFlags(QPaintEngine *engine)
A class to represent a 2D point.
void setExteriorRing(QgsCurve *ring) override
Sets the exterior ring of the polygon.
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
QgsProjectMetadata metadata
A rectangle specified with double values.
double xMinimum() const
Returns the x minimum value (left side of rectangle).
double yMinimum() const
Returns the y minimum value (bottom side of rectangle).
double width() const
Returns the width of the rectangle.
double yMaximum() const
Returns the y maximum value (top side of rectangle).
QgsPointXY center() const
Returns the center point of the rectangle.
double height() const
Returns the height of the rectangle.
A boolean settings entry.
static QgsSettingsTreeNode * sTreeLayout
This class contains information how to simplify geometries fetched from a vector layer.
void setThreshold(float threshold)
Sets the simplification threshold of the vector layer managed.
void setForceLocalOptimization(bool localOptimization)
Sets where the simplification executes, after fetch the geometries from provider, or when supported,...
void setSimplifyHints(Qgis::VectorRenderingSimplificationFlags simplifyHints)
Sets the simplification hints of the vector layer managed.
void setSimplifyAlgorithm(Qgis::VectorSimplificationAlgorithm simplifyAlgorithm)
Sets the local simplification algorithm of the vector layer managed.
std::unique_ptr< std::remove_pointer< GDALDatasetH >::type, GDALDatasetCloser > dataset_unique_ptr
Scoped GDAL dataset.
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 Q_NOWARN_DEPRECATED_POP
#define Q_NOWARN_DEPRECATED_PUSH
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
QString nameForLayerWithItems(const QList< QGraphicsItem * > &items, unsigned int layerId)
Contains details of a particular input component to be used during PDF composition.
QString sourcePdfPath
File path to the (already created) PDF to use as the source for this component layer.
QString mapLayerId
Associated map layer ID, or an empty string if this component layer is not associated with a map laye...
QPainter::CompositionMode compositionMode
Component composition mode.
QString group
Optional group name, for arranging layers in top-level groups.
QString name
User-friendly name for the generated PDF layer.
double opacity
Component opacity.
Contains details of a control point used during georeferencing GeoPDF outputs.
QgsAbstractMetadataBase::KeywordMap keywords
Metadata keyword map.
bool useIso32000ExtensionFormatGeoreferencing
true if ISO32000 extension format georeferencing should be used.
QMap< QString, QString > layerIdToPdfLayerTreeNameMap
Optional map of map layer ID to custom layer tree name to show in the created PDF file.
bool useOgcBestPracticeFormatGeoreferencing
true if OGC "best practice" format georeferencing should be used.
QDateTime creationDateTime
Metadata creation datetime.
QSizeF pageSizeMm
Page size, in millimeters.
QList< QgsAbstractGeoPdfExporter::GeoReferencedSection > georeferencedSections
List of georeferenced sections.
QStringList layerTreeGroupOrder
Specifies the ordering of layer tree groups in the generated GeoPDF file.
QString author
Metadata author tag.
QMap< QString, bool > initialLayerVisibility
Optional map of map layer ID to initial visibility state.
QString producer
Metadata producer tag.
QString creator
Metadata creator tag.
QSet< QString > mutuallyExclusiveGroups
Contains a list of group names which should be considered as mutually exclusive.
QMap< QString, QString > customLayerTreeGroups
Optional map of map layer ID to custom logical layer tree group in created PDF file.
bool includeFeatures
true if feature vector information (such as attributes) should be exported.
QStringList layerOrder
Optional list of layer IDs, in the order desired to appear in the generated GeoPDF file.
QString subject
Metadata subject tag.
QString title
Metadata title tag.
QgsCoordinateReferenceSystem crs
Coordinate reference system for georeferenced section.
QgsPolygon pageBoundsPolygon
Bounds of the georeferenced section on the page, in millimeters, as a free-form polygon.
QList< QgsAbstractGeoPdfExporter::ControlPoint > controlPoints
List of control points corresponding to this georeferenced section.
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...
QgsLayoutRenderContext::Flags 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 '.')
QString directory
Target folder.
int page
Page number, where 0 = first page.
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.
QStringList exportThemes
Optional list of map themes to export as GeoPDF layer groups.
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.
bool writeGeoPdf
true if GeoPDF 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,...
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.
double dpi
Resolution to export layout at. If dpi <= 0 the default layout dpi will be used.
QgsLayoutRenderContext::Flags flags
Layout context flags, which control how the export will be created.
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::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.
QgsLayoutRenderContext::Flags flags
Layout context flags, which control how the export will be created.
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.
QString name
User-friendly name for the export layer.
QString groupName
Associated group name, if this layer is associated with an export group.