def TOMsExportAtlas(self, printProposalObject): # TH (180608): Export function to deal with atlases settings = QSettings() format = self.dialogui.comboBox_fileformat.itemData(self.dialogui.comboBox_fileformat.currentIndex()) # TH (180608): Check to see whether or not the Composer is an Atlas currPrintLayout = self.layoutView currLayoutAtlas = currPrintLayout.atlas() success = False # https://gis.stackexchange.com/questions/77848/programmatically-load-composer-from-template-and-generate-atlas-using-pyqgis?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa self.TOMsSetAtlasValues(currPrintLayout) currRevisionDate = self.proposalsManager.date() # get the map tiles that are affected by the Proposal # self.getProposalTileList(currProposalID, currRevisionDate) proposalTileDictionaryForDate = printProposalObject.getProposalTileDictionaryForDate(currRevisionDate) """self.tileSet = set( proposalTileDictionaryForDate)""" # TODO: Change around use of tileSet - also might be good to have a current proposal as an object in proposalManager... # Now check which tiles to use self.tilesToPrint = self.TOMsChooseTiles(proposalTileDictionaryForDate) if len(self.tilesToPrint) == 0: return # get the output location dirName = QFileDialog.getExistingDirectory( self.iface.mainWindow(), self.tr("Export Composition"), settings.value("/instantprint/lastdir", ""), QFileDialog.ShowDirsOnly ) if not dirName: return settings.setValue("/instantprint/lastdir", dirName) tileIDList = "" firstTile = True for tile in self.tilesToPrint: if firstTile: tileIDList = str(tile.attribute("id")) firstTile = False else: tileIDList = tileIDList + ',' + str(tile.attribute("id")) currLayoutAtlas.setFilterFeatures(True) currLayoutAtlas.setFilterExpression(' "id" in ({tileList})'.format(tileList=tileIDList)) composerRevisionNr = currPrintLayout.itemById('revisionNr') composerEffectiveDate = currPrintLayout.itemById('effectiveDate') composerProposalStatus = currPrintLayout.itemById('proposalStatus') if composerProposalStatus is not None: composerProposalStatus.setText(self.proposalForPrintingStatusText) else: QMessageBox.warning(self.iface.mainWindow(), self.tr("Missing label in Layout"), self.tr("Missing label 'proposalStatus'")) composerPrintTypeDetails = currPrintLayout.itemById('printTypeDetails') if composerPrintTypeDetails is not None: composerPrintTypeDetails.setText(self.proposalPrintTypeDetails) else: QMessageBox.warning(self.iface.mainWindow(), self.tr("Missing label in Layout"), self.tr("Missing label 'printTypeDetails'")) # currProposalTitle, currProposalOpenDate = self.getProposalTitle(currProposalID) #printProposal = printProposalObject currProposalTitle = printProposalObject.getProposalTitle() currProposalOpenDate = printProposalObject.getProposalOpenDate() if printProposalObject.thisProposalNr == 0: currProposalTitle = "CurrentRestrictions_({date})".format( date=self.proposalsManager.date().toString('yyyyMMMdd')) TOMsMessageLog.logMessage("In TOMsExportAtlas. Now printing " + str(currLayoutAtlas.count()) + " items ....", level=Qgis.Info) currLayoutAtlas.setEnabled(True) currLayoutAtlas.updateFeatures() currLayoutAtlas.beginRender() altasFeatureFound = currLayoutAtlas.first() while altasFeatureFound: currTileNr = int(currLayoutAtlas.nameForPage(currLayoutAtlas.currentFeatureNumber())) currLayoutAtlas.refreshCurrentFeature() #tileWithDetails = self.tileFromTileSet(currTileNr) tileWithDetails = proposalTileDictionaryForDate[currTileNr] if tileWithDetails == None: TOMsMessageLog.logMessage("In TOMsExportAtlas. Tile with details not found ....", level=Qgis.Info) QMessageBox.warning(self.iface.mainWindow(), self.tr("Print Failed"), self.tr("Could not find details for " + str(currTileNr))) break TOMsMessageLog.logMessage("In TOMsExportAtlas. tile nr: " + str(currTileNr) + " RevisionNr: " + str( tileWithDetails["RevisionNr"]) + " RevisionDate: " + str(tileWithDetails["LastRevisionDate"]), level=Qgis.Info) if self.proposalForPrintingStatusText == "CONFIRMED": composerRevisionNr.setText(str(tileWithDetails["RevisionNr"])) composerEffectiveDate.setText( '{date}'.format(date=tileWithDetails["LastRevisionDate"].toString('dd-MMM-yyyy'))) else: composerRevisionNr.setText(str(tileWithDetails["RevisionNr"] + 1)) # For the Proposal, use the current view date composerEffectiveDate.setText( '{date}'.format(date=self.openDateForPrintProposal.toString('dd-MMM-yyyy'))) filename = currProposalTitle + "_" + str( currTileNr) + "." + self.dialogui.comboBox_fileformat.currentText().lower() outputFile = os.path.join(dirName, filename) exporter = QgsLayoutExporter(currLayoutAtlas.layout()) if self.dialogui.comboBox_fileformat.currentText().lower() == u"pdf": result = exporter.exportToPdf(outputFile, QgsLayoutExporter.PdfExportSettings()) # success = currLayoutAtlas.composition().exportAsPDF(outputFile) else: result = exporter.exportToImage(outputFile, 'png', QgsLayoutExporter.ImageExportSettings()) """image = currLayoutAtlas.composition().printPageAsRaster(0) if not image.isNull(): success = image.save(outputFile)""" if result != QgsLayoutExporter.Success: QMessageBox.warning(self.iface.mainWindow(), self.tr("Print Failed"), self.tr("Failed to print " + exporter.errorFile())) break altasFeatureFound = currLayoutAtlas.next() currLayoutAtlas.endRender() QMessageBox.information(self.iface.mainWindow(), "Information", ("Printing completed"))
def create_qgis_pdf_output( impact_report, output_path, layout, file_format, metadata): """Produce PDF output using QgsLayout. :param output_path: The output path. :type output_path: str :param layout: QGIS Layout object. :type layout: qgis.core.QgsPrintLayout :param qgis_composition_context: QGIS Composition context used by renderer. :type qgis_composition_context: safe.report.impact_report. QgsLayoutContext :param file_format: file format of map output, PDF or PNG. :type file_format: 'pdf', 'png' :param metadata: The component metadata. :type metadata: QgisComposerComponentsMetadata :return: Generated output path. :rtype: str """ # make sure directory is created dirname = os.path.dirname(output_path) if not os.path.exists(dirname): os.makedirs(dirname) qgis_composition_context = impact_report.qgis_composition_context aggregation_summary_layer = ( impact_report.impact_function.aggregation_summary) # process atlas generation print_atlas = setting('print_atlas_report', False, bool) if layout.atlas().enabled() and ( print_atlas and aggregation_summary_layer): output_path = atlas_renderer( layout, aggregation_summary_layer, output_path, file_format) # for QGIS layout only pdf and png output are available elif file_format == QgisComposerComponentsMetadata.OutputFormat.PDF: try: exporter = QgsLayoutExporter(layout) settings = QgsLayoutExporter.PdfExportSettings() settings.dpi = metadata.page_dpi settings.rasterizeWholeImage = \ qgis_composition_context.save_as_raster # settings.forceVectorOutput = False # settings.exportMetadata = True # TODO: ABP: check that page size is set on the pages res = exporter.exportToPdf(output_path, settings) if res != QgsLayoutExporter.Success: LOGGER.error('Error exporting to {}'.format( exporter.errorFile())) return None except Exception as exc: LOGGER.error(exc) return None elif file_format == QgisComposerComponentsMetadata.OutputFormat.PNG: # TODO: implement PNG generation raise Exception('Not yet supported') return output_path
def create_qgis_pdf_output( impact_report, output_path, layout, file_format, metadata): """Produce PDF output using QgsLayout. :param output_path: The output path. :type output_path: str :param layout: QGIS Layout object. :type layout: qgis.core.QgsPrintLayout :param qgis_composition_context: QGIS Composition context used by renderer. :type qgis_composition_context: safe.report.impact_report. QgsLayoutContext :param file_format: file format of map output, PDF or PNG. :type file_format: 'pdf', 'png' :param metadata: The component metadata. :type metadata: QgisComposerComponentsMetadata :return: Generated output path. :rtype: str """ # make sure directory is created dirname = os.path.dirname(output_path) if not os.path.exists(dirname): os.makedirs(dirname) qgis_composition_context = impact_report.qgis_composition_context aggregation_summary_layer = ( impact_report.impact_function.aggregation_summary) # process atlas generation print_atlas = setting('print_atlas_report', False, bool) if layout.atlas().enabled() and ( print_atlas and aggregation_summary_layer): output_path = atlas_renderer( layout, aggregation_summary_layer, output_path, file_format) # for QGIS layout only pdf and png output are available elif file_format == QgisComposerComponentsMetadata.OutputFormat.PDF: try: exporter = QgsLayoutExporter(layout) settings = QgsLayoutExporter.PdfExportSettings() settings.dpi = metadata.page_dpi settings.rasterizeWholeImage = \ qgis_composition_context.save_as_raster # settings.forceVectorOutput = False # settings.exportMetadata = True # TODO: ABP: check that page size is set on the pages res = exporter.exportToPdf(output_path, settings) if res != QgsLayoutExporter.Success: LOGGER.error('Error exporting to {}'.format( exporter.errorFile())) return None except Exception as exc: LOGGER.error(exc) return None elif file_format == QgisComposerComponentsMetadata.OutputFormat.PNG: # TODO: implement PNG generation raise Exception('Not yet supported') return output_path