Example #1
0
def make_pdf():
    canvas = QgsMapCanvas()
    # Load our project
    QgsProject.instance().read(QFileInfo(project_path))
    bridge = QgsLayerTreeMapCanvasBridge(QgsProject.instance().layerTreeRoot(),
                                         canvas)
    bridge.setCanvasLayers()

    template_file = file(template_path)
    template_content = template_file.read()
    template_file.close()
    document = QDomDocument()
    document.setContent(template_content)
    composition = QgsComposition(canvas.mapSettings())
    # You can use this to replace any string like this [key]
    # in the template with a new value. e.g. to replace
    # [date] pass a map like this {'date': '1 Jan 2012'}
    substitution_map = {'DATE_TIME_START': 'foo', 'DATE_TIME_END': 'bar'}
    composition.loadFromTemplate(document, substitution_map)
    # You must set the id in the template
    map_item = composition.getComposerItemById('map')
    map_item.setMapCanvas(canvas)
    map_item.zoomToExtent(canvas.extent())
    # You must set the id in the template
    legend_item = composition.getComposerItemById('legend')
    legend_item.updateLegend()
    composition.refreshItems()
    composition.exportAsPDF('report.pdf')
    QgsProject.instance().clear()
def make_pdf():
    canvas = QgsMapCanvas()
    # Load our project
    QgsProject.instance().read(QFileInfo(project_path))
    bridge = QgsLayerTreeMapCanvasBridge(
        QgsProject.instance().layerTreeRoot(), canvas)
    bridge.setCanvasLayers()
    if canvas.layerCount() < 1:
        print 'No layers loaded from this project, exiting.'
        return
    print canvas.mapSettings().extent().toString()
    template_file = file(template_path)
    template_content = template_file.read()
    template_file.close()
    document = QDomDocument()
    document.setContent(template_content)
    composition = QgsComposition(canvas.mapSettings())
    # You can use this to replace any string like this [key]
    # in the template with a new value. e.g. to replace
    # [date] pass a map like this {'date': '1 Jan 2012'}
    substitution_map = {
        'DATE_TIME_START': TIME_START,
        'DATE_TIME_END': TIME_STOP}
    composition.loadFromTemplate(document, substitution_map)
    # You must set the id in the template
    map_item = composition.getComposerItemById('map')
    map_item.setMapCanvas(canvas)
    map_item.zoomToExtent(canvas.extent())
    # You must set the id in the template
    legend_item = composition.getComposerItemById('legend')
    legend_item.updateLegend()
    composition.refreshItems()
    composition.exportAsPDF(
        '/home/web/reports/pdf/%s/%s.pdf' % (TIME_SLICE, LABEL))
    QgsProject.instance().clear()
Example #3
0
 def export_pdf(self, title=''):
     '''
     Export Composition (map view and checked layers) to PDF
     '''
     title = self.active_scenario.name if self.active_scenario else ''
     dialog = ExportPDFDialog(title=title, parent=self)
     result = dialog.exec_()
     ok = result == QtGui.QDialog.Accepted
     if not ok:
         return
     title = dialog.title
     date = dialog.date
     filepath = browse_file(None, 'Export', PDF_FILTER, save=True, 
                            parent=self)
     if not filepath:
         return
     bridge = QgsLayerTreeMapCanvasBridge(
         QgsProject.instance().layerTreeRoot(), self.canvas)
     bridge.setCanvasLayers()
 
     template_file = file(REPORT_TEMPLATE_PATH)
     template_content = template_file.read()
     template_file.close()
     document = QDomDocument()
     document.setContent(template_content)
     composition = QgsComposition(self.canvas.mapSettings())
     # You can use this to replace any string like this [key]
     # in the template with a new value. e.g. to replace
     # [date] pass a map like this {'date': '1 Jan 2012'}
     substitution_map = {
         'TITLE': title,
         'DATE_TIME': date}
     composition.loadFromTemplate(document, substitution_map)
     # You must set the id in the template
     map_item = composition.getComposerItemById('map')
     map_item.setMapCanvas(self.canvas)
     map_item.zoomToExtent(self.canvas.extent())
     # You must set the id in the template
     legend_item = composition.getComposerItemById('legend')
     legend_item.updateLegend()
     composition.refreshItems()
     composition.exportAsPDF(filepath)
     if sys.platform.startswith('darwin'):
         subprocess.call(('open', filepath))
     elif os.name == 'nt':
         os.startfile(filepath)
     elif os.name == 'posix':
         subprocess.call(('xdg-open', filepath))
Example #4
0
    def load_composition(self):
        """ Creates the composition object (which is needed for creating the file) from the template file.
            
            :returns: the composition object
            :rtype: QgsComposition
        """
        template_path = get_plugin_path() + self.templates[
            self.dockwidget.comboBox_template.currentText()]
        template_file = open(template_path, "r")
        content = template_file.read()
        template_file.close()

        # the method from QgsComposition for loading the template needs to be a QDomDocument
        document = QDomDocument()
        document.setContent(content)

        # composition = QgsComposition(iface.mapCanvas().mapSettings()) does not work
        #TODO: is deprecated but works ...fix in new version https://hub.qgis.org/issues/11077
        composition = QgsComposition(iface.mapCanvas().mapRenderer())
        if not composition.loadFromTemplate(document):
            iface.messageBar().pushMessage("Error while loading template!")
            return

        # set map
        map_item = composition.getComposerItemById("map")
        map_item.setMapCanvas(iface.mapCanvas())
        map_item.zoomToExtent(iface.mapCanvas().extent())

        # set legend
        try:
            legend_item = composition.getComposerItemById("legend")
            legend_item.updateLegend()
        except AttributeError:  # in case first template was selected
            pass

        composition.refreshItems()
        return composition
Example #5
0
template_content = template_file.read()
template_file.close()
document = QDomDocument()
document.setContent(template_content)
ms = canvas.mapSettings()
composition = QgsComposition(ms)
composition.loadFromTemplate(document, {})
# You must set the id in the template
#map_item = composition.getComposerItemById('map')
map_item = composition.getComposerMapById(1)
#map_item.setMapCanvas(canvas)
#map_item.zoomToExtent(canvas.extent())
# You must set the id in the template
#legend_item = composition.getComposerItemById('legend')
#legend_item.updateLegend()
composition.refreshItems()

dpmm = dpi / 25.4
#width = int(dpmm * composition.paperWidth())
width = int(1400)
print(width)

#height = int(dpmm * 141)
height = int(1000)
print(height)

# create output image and initialize it
image = QImage(QSize(width, height), QImage.Format_ARGB32)
#image.setDotsPerMeterX(dpmm * 1000)
#image.setDotsPerMeterY(dpmm * 1000)
#image.fill(0)
Example #6
0
    def exportToPdf(self, print_context, targetFile=None):
        self.iface.mapCanvas().setDestinationCrs(
            self.settings_instance.projection.crs())
        myComposition = QgsComposition(self.iface.mapCanvas().mapSettings())
        template = self.env.get_template(print_context['template'])

        custom_qpt = template.render(CONTEXT=print_context)
        myDocument = QDomDocument()
        myDocument.setContent(custom_qpt)
        myComposition.loadFromTemplate(myDocument)

        suggestedFile = os.path.join(
            self.settings_instance.projectFolderPath.text(),
            print_context['title'] + ".pdf")
        if not targetFile:
            targetFile = QFileDialog.getSaveFileName(
                None, "Export " + print_context['job'], suggestedFile, "*.pdf")
            interactive = True
            if not targetFile:
                return
        else:
            interactive = None

        outputDir = tempfile.gettempdir()

        with open(os.path.join(targetFile + '.qpt'), "wb") as qpt_file:
            qpt_file.write(custom_qpt)

        if print_context['type'] == 'report':
            myComposition.exportAsPDF(targetFile)

        elif print_context['type'] == 'map':
            print myComposition.getComposerMapById(0)
            print myComposition.getComposerItemById('5')

            for composer_map in myComposition.composerMapItems():
                print composer_map, composer_map.id()

            fdtm_extent = None
            for layer in [
                    self.settings_instance.EPpLayer,
                    self.settings_instance.EApLayer,
                    self.settings_instance.WRLayer,
                    self.settings_instance.WDSLayer
            ]:
                if layer.featureCount() > 0:
                    if fdtm_extent:
                        fdtm_extent.combineExtentWith(layer.extent())
                    else:
                        fdtm_extent = layer.extent()
            fdtm_extent.scale(1.1)
            composer_map.zoomToExtent(fdtm_extent)
            composer_map.updateItem()
            myComposition.refreshItems()

            myComposition.exportAsPDF(targetFile)

        elif print_context['type'] == 'mapppp':
            print print_context
            myComposition = QgsComposition(
                self.iface.mapCanvas().mapSettings())
            myComposition.setPlotStyle(QgsComposition.Print)
            myComposition.setPaperSize(297, 210)
            composer_map = QgsComposerMap(myComposition, 10, 10, 190, 190)
            fdtm_extent = self.settings_instance.EPpLayer.extent()
            for layer in [
                    self.settings_instance.EApLayer,
                    self.settings_instance.WRLayer,
                    self.settings_instance.WDSLayer
            ]:
                fdtm_extent.combineExtentWith(layer.extent())
            composer_map.zoomToExtent(fdtm_extent)
            composer_map.updateItem()
            myComposition.addItem(composer_map)

            table = QgsComposerAttributeTable(myComposition)
            table.setItemPosition(205, 170)
            table.setVectorLayer(QgsMapLayerRegistry.instance().mapLayer(
                print_context['id']))
            table.setMaximumNumberOfFeatures(20)
            table.setFilterFeatures(True)
            col1 = QgsComposerTableColumn()
            col1.setAttribute('types')
            col1.setHeading("types")
            col2 = QgsComposerTableColumn()
            col2.setAttribute('project units')
            col2.setHeading("project units")
            col3 = QgsComposerTableColumn()
            col3.setAttribute('Areas')
            col3.setHeading("Areas")
            col4 = QgsComposerTableColumn()
            col4.setAttribute('Lengths')
            col4.setHeading("Lengths")
            col5 = QgsComposerTableColumn()
            col5.setAttribute('Cost')
            col5.setHeading("Cost")
            table.setColumns([col1, col2, col3, col4, col5])
            myComposition.addItem(table)

            myComposition.exportAsPDF(targetFile)

        elif print_context['type'] == 'atlas':

            myComposition.setAtlasMode(QgsComposition.ExportAtlas)
            for composer_map in myComposition.composerMapItems():
                print composer_map, composer_map.id()

            atlas = myComposition.atlasComposition()
            atlas.setComposerMap(composer_map)  #DEPRECATED
            atlas.setPredefinedScales(self.PREDEFINED_SCALES)
            composer_map.setAtlasDriven(True)
            composer_map.setAtlasScalingMode(QgsComposerMap.Predefined)

            atlas.beginRender()
            rendered_pdf = []
            progress = progressBar(self, "exporting " + print_context['job'],
                                   atlas.numFeatures())
            for i in range(0, atlas.numFeatures()):
                atlas.prepareForFeature(i)
                current_filename = atlas.currentFilename()
                file_name = '_'.join(current_filename.split())
                file_path = '%s.pdf' % file_name
                path = os.path.join(outputDir, file_path)
                myComposition.exportAsPDF(path)
                rendered_pdf.append(path)
                progress.setStep(i)
            progress.stop(print_context['job'] + "exported to " + targetFile)
            atlas.endRender()

            merge_pdfs(rendered_pdf, targetFile)

        if interactive:
            open_file(targetFile)

        return targetFile