Exemplo n.º 1
0
    def testSaveLoadTemplate(self):
        tmpfile = os.path.join(self.basetestpath, 'testTemplate.qpt')

        p = QgsProject()
        l = QgsLayout(p)
        l.initializeDefaults()

        # add some items
        item1 = QgsLayoutItemLabel(l)
        item1.setId('xxyyxx')
        item1.attemptMove(QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters))
        item1.attemptResize(QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        l.addItem(item1)
        item2 = QgsLayoutItemLabel(l)
        item2.setId('zzyyzz')
        item2.attemptMove(QgsLayoutPoint(1.4, 1.8, QgsUnitTypes.LayoutCentimeters))
        item2.attemptResize(QgsLayoutSize(2.8, 2.2, QgsUnitTypes.LayoutCentimeters))
        l.addItem(item2)

        # multiframe
        multiframe1 = QgsLayoutItemHtml(l)
        multiframe1.setHtml('mf1')
        l.addMultiFrame(multiframe1)
        frame1 = QgsLayoutFrame(l, multiframe1)
        frame1.setId('frame1')
        frame1.attemptMove(QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters))
        frame1.attemptResize(QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        multiframe1.addFrame(frame1)

        multiframe2 = QgsLayoutItemHtml(l)
        multiframe2.setHtml('mf2')
        l.addMultiFrame(multiframe2)
        frame2 = QgsLayoutFrame(l, multiframe2)
        frame2.setId('frame2')
        frame2.attemptMove(QgsLayoutPoint(1.4, 1.8, QgsUnitTypes.LayoutCentimeters))
        frame2.attemptResize(QgsLayoutSize(2.8, 2.2, QgsUnitTypes.LayoutCentimeters))
        multiframe2.addFrame(frame2)

        uuids = {item1.uuid(), item2.uuid(), frame1.uuid(), frame2.uuid(), multiframe1.uuid(), multiframe2.uuid()}
        original_uuids = {item1.uuid(), item2.uuid(), frame1.uuid(), frame2.uuid()}

        self.assertTrue(l.saveAsTemplate(tmpfile, QgsReadWriteContext()))

        l2 = QgsLayout(p)
        with open(tmpfile) as f:
            template_content = f.read()
        doc = QDomDocument()
        doc.setContent(template_content)

        # adding to existing items
        new_items, ok = l2.loadFromTemplate(doc, QgsReadWriteContext(), False)
        self.assertTrue(ok)
        self.assertEqual(len(new_items), 4)
        items = l2.items()
        multiframes = l2.multiFrames()
        self.assertEqual(len(multiframes), 2)
        self.assertTrue([i for i in items if i.id() == 'xxyyxx'])
        self.assertTrue([i for i in items if i.id() == 'zzyyzz'])
        self.assertTrue([i for i in items if i.id() == 'frame1'])
        self.assertTrue([i for i in items if i.id() == 'frame2'])
        self.assertTrue([i for i in multiframes if i.html() == 'mf1'])
        self.assertTrue([i for i in multiframes if i.html() == 'mf2'])
        self.assertTrue(new_items[0] in l2.items())
        self.assertTrue(new_items[1] in l2.items())
        self.assertTrue(new_items[2] in l2.items())
        self.assertTrue(new_items[3] in l2.items())

        # double check that new items have a unique uid
        self.assertNotIn(new_items[0].uuid(), uuids)
        uuids.add(new_items[0].uuid())
        self.assertNotIn(new_items[1].uuid(), uuids)
        uuids.add(new_items[1].uuid())
        self.assertNotIn(new_items[2].uuid(), uuids)
        uuids.add(new_items[2].uuid())
        self.assertNotIn(new_items[3].uuid(), uuids)
        uuids.add(new_items[3].uuid())

        self.assertNotIn(multiframes[0].uuid(), [multiframe1.uuid(), multiframe2.uuid()])
        self.assertNotIn(multiframes[1].uuid(), [multiframe1.uuid(), multiframe2.uuid()])
        new_multiframe1 = [i for i in multiframes if i.html() == 'mf1'][0]
        self.assertEqual(new_multiframe1.layout(), l2)
        new_multiframe2 = [i for i in multiframes if i.html() == 'mf2'][0]
        self.assertEqual(new_multiframe2.layout(), l2)
        new_frame1 = sip.cast([i for i in items if i.id() == 'frame1'][0], QgsLayoutFrame)
        new_frame2 = sip.cast([i for i in items if i.id() == 'frame2'][0], QgsLayoutFrame)
        self.assertEqual(new_frame1.multiFrame(), new_multiframe1)
        self.assertEqual(new_multiframe1.frames()[0].uuid(), new_frame1.uuid())
        self.assertEqual(new_frame2.multiFrame(), new_multiframe2)
        self.assertEqual(new_multiframe2.frames()[0].uuid(), new_frame2.uuid())

        # adding to existing items
        new_items2, ok = l2.loadFromTemplate(doc, QgsReadWriteContext(), False)
        self.assertTrue(ok)
        self.assertEqual(len(new_items2), 4)
        items = l2.items()
        self.assertEqual(len(items), 8)
        multiframes2 = l2.multiFrames()
        self.assertEqual(len(multiframes2), 4)
        multiframes2 = [m for m in l2.multiFrames() if not m.uuid() in [new_multiframe1.uuid(), new_multiframe2.uuid()]]
        self.assertEqual(len(multiframes2), 2)
        self.assertTrue([i for i in items if i.id() == 'xxyyxx'])
        self.assertTrue([i for i in items if i.id() == 'zzyyzz'])
        self.assertTrue([i for i in items if i.id() == 'frame1'])
        self.assertTrue([i for i in items if i.id() == 'frame2'])
        self.assertTrue([i for i in multiframes2 if i.html() == 'mf1'])
        self.assertTrue([i for i in multiframes2 if i.html() == 'mf2'])
        self.assertTrue(new_items[0] in l2.items())
        self.assertTrue(new_items[1] in l2.items())
        self.assertTrue(new_items[2] in l2.items())
        self.assertTrue(new_items[3] in l2.items())
        self.assertTrue(new_items2[0] in l2.items())
        self.assertTrue(new_items2[1] in l2.items())
        self.assertTrue(new_items2[2] in l2.items())
        self.assertTrue(new_items2[3] in l2.items())
        self.assertNotIn(new_items2[0].uuid(), uuids)
        uuids.add(new_items[0].uuid())
        self.assertNotIn(new_items2[1].uuid(), uuids)
        uuids.add(new_items[1].uuid())
        self.assertNotIn(new_items2[2].uuid(), uuids)
        uuids.add(new_items[2].uuid())
        self.assertNotIn(new_items2[3].uuid(), uuids)
        uuids.add(new_items[3].uuid())

        self.assertNotIn(multiframes2[0].uuid(), [multiframe1.uuid(), multiframe2.uuid(), new_multiframe1.uuid(), new_multiframe2.uuid()])
        self.assertNotIn(multiframes2[1].uuid(), [multiframe1.uuid(), multiframe2.uuid(), new_multiframe1.uuid(), new_multiframe2.uuid()])

        new_multiframe1b = [i for i in multiframes2 if i.html() == 'mf1'][0]
        self.assertEqual(new_multiframe1b.layout(), l2)
        new_multiframe2b = [i for i in multiframes2 if i.html() == 'mf2'][0]
        self.assertEqual(new_multiframe2b.layout(), l2)
        new_frame1b = sip.cast([i for i in items if i.id() == 'frame1' and i.uuid() != new_frame1.uuid()][0], QgsLayoutFrame)
        new_frame2b = sip.cast([i for i in items if i.id() == 'frame2' and i.uuid() != new_frame2.uuid()][0], QgsLayoutFrame)
        self.assertEqual(new_frame1b.multiFrame(), new_multiframe1b)
        self.assertEqual(new_multiframe1b.frames()[0].uuid(), new_frame1b.uuid())
        self.assertEqual(new_frame2b.multiFrame(), new_multiframe2b)
        self.assertEqual(new_multiframe2b.frames()[0].uuid(), new_frame2b.uuid())

        # clearing existing items
        new_items3, ok = l2.loadFromTemplate(doc, QgsReadWriteContext(), True)
        new_multiframes = l2.multiFrames()
        self.assertTrue(ok)
        self.assertEqual(len(new_items3), 5) # includes page
        self.assertEqual(len(new_multiframes), 2)
        items = l2.items()
        self.assertTrue([i for i in items if isinstance(i, QgsLayoutItem) and i.id() == 'xxyyxx'])
        self.assertTrue([i for i in items if isinstance(i, QgsLayoutItem) and i.id() == 'zzyyzz'])
        self.assertTrue([i for i in items if isinstance(i, QgsLayoutItem) and i.id() == 'frame1'])
        self.assertTrue([i for i in items if isinstance(i, QgsLayoutItem) and i.id() == 'frame2'])
        self.assertTrue(new_items3[0] in l2.items())
        self.assertTrue(new_items3[1] in l2.items())
        self.assertTrue(new_items3[2] in l2.items())
        self.assertTrue(new_items3[3] in l2.items())
        new_multiframe1 = [i for i in new_multiframes if i.html() == 'mf1'][0]
        new_multiframe2 = [i for i in new_multiframes if i.html() == 'mf2'][0]

        new_frame1 = sip.cast([i for i in items if isinstance(i, QgsLayoutItem) and i.id() == 'frame1'][0], QgsLayoutFrame)
        new_frame2 = sip.cast([i for i in items if isinstance(i, QgsLayoutItem) and i.id() == 'frame2'][0], QgsLayoutFrame)
        self.assertEqual(new_frame1.multiFrame(), new_multiframe1)
        self.assertEqual(new_multiframe1.frames()[0].uuid(), new_frame1.uuid())
        self.assertEqual(new_frame2.multiFrame(), new_multiframe2)
        self.assertEqual(new_multiframe2.frames()[0].uuid(), new_frame2.uuid())
Exemplo n.º 2
0
    def imprimirPlanol(self, x, y, escala, rotacion, midaPagina, templateFile,
                       fitxerSortida, tipusSortida):
        tInicial = time.time()

        template = QFile(templateFile)
        doc = QDomDocument()
        doc.setContent(template, False)

        layout = QgsLayout(self.project)
        # page=QgsLayoutItemPage(layout)
        # page.setPageSize(midaPagina)
        # layout.pageCollection().addPage(page)

        # layout.initializeDefaults()
        # p=layout.pageCollection().pages()[0]
        # p.setPageSize(midaPagina)

        context = QgsReadWriteContext()
        [items, ok] = layout.loadFromTemplate(doc, context)
        # p=layout.pageCollection().pages()[0]
        # p.setPageSize(midaPagina)

        if ok:
            refMap = layout.referenceMap()

            titol = layout.itemById('idNomMapa')
            dataMapa = layout.itemById('idData')
            if self.leTitol.text() != '':
                titol.setText(self.leTitol.text())  #comentat pk peta
            else:
                titol.setText('')
            try:
                t = time.localtime()
                dataMapa.setText(strftime('%b-%d-%Y %H:%M', t))
            except:
                pass

            rect = refMap.extent()
            vector = QgsVector(x - rect.center().x(), y - rect.center().y())
            rect += vector
            refMap.setExtent(rect)
            refMap.setScale(escala)
            refMap.setMapRotation(rotacion)
            #Depenent del tipus de sortida...

            exporter = QgsLayoutExporter(layout)
            # image_settings = exporter.ImageExportSettings()
            # image_settings.dpi = 30

            # result = exporter.exportToImage('d:/dropbox/qpic/preview.png',  image_settings)
            # imatge = QPixmap('d:/dropbox/qpic/preview.png')
            # self.ui.lblImatgeResultat.setPixmap(imatge)

            if tipusSortida == 'PDF':
                settings = QgsLayoutExporter.PdfExportSettings()
                settings.dpi = 300
                settings.exportMetadata = False

                # fitxerSortida='d:/sortida_'+timestamp+'.PDF'
                fitxerSortida += '.PDF'
                result = exporter.exportToPdf(
                    fitxerSortida, settings)  #Cal desar el resultat (???)

                print(fitxerSortida)

            if tipusSortida == 'PNG':
                settings = QgsLayoutExporter.ImageExportSettings()
                settings.dpi = 300

                # fitxerSortida='d:/sortida_'+timestamp+'.PNG'
                fitxerSortida += '.PNG'
                result = exporter.exportToImage(
                    fitxerSortida, settings)  #Cal desar el resultat (???)

            #Obra el document si està marcat checkObrirResultat
            QDesktopServices().openUrl(QUrl(fitxerSortida))

            segonsEmprats = round(time.time() - tInicial, 1)  #???
            layersTemporals = self.project.mapLayersByName(
                "Capa temporal d'impressió")

            estatDirtybit = self.parent.canvisPendents
            for layer in layersTemporals:
                self.project.removeMapLayer(layer.id())
            self.parent.setDirtyBit(estatDirtybit)
Exemplo n.º 3
0
    def testSaveLoadTemplate(self):
        tmpfile = os.path.join(self.basetestpath, 'testTemplate.qpt')

        p = QgsProject()
        l = QgsLayout(p)
        l.initializeDefaults()

        # add some items
        item1 = QgsLayoutItemLabel(l)
        item1.setId('xxyyxx')
        item1.attemptMove(QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters))
        item1.attemptResize(
            QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        l.addItem(item1)
        item2 = QgsLayoutItemLabel(l)
        item2.setId('zzyyzz')
        item2.attemptMove(
            QgsLayoutPoint(1.4, 1.8, QgsUnitTypes.LayoutCentimeters))
        item2.attemptResize(
            QgsLayoutSize(2.8, 2.2, QgsUnitTypes.LayoutCentimeters))
        l.addItem(item2)

        # multiframe
        multiframe1 = QgsLayoutItemHtml(l)
        multiframe1.setHtml('mf1')
        l.addMultiFrame(multiframe1)
        frame1 = QgsLayoutFrame(l, multiframe1)
        frame1.setId('frame1')
        frame1.attemptMove(QgsLayoutPoint(4, 8,
                                          QgsUnitTypes.LayoutMillimeters))
        frame1.attemptResize(
            QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        multiframe1.addFrame(frame1)

        multiframe2 = QgsLayoutItemHtml(l)
        multiframe2.setHtml('mf2')
        l.addMultiFrame(multiframe2)
        frame2 = QgsLayoutFrame(l, multiframe2)
        frame2.setId('frame2')
        frame2.attemptMove(
            QgsLayoutPoint(1.4, 1.8, QgsUnitTypes.LayoutCentimeters))
        frame2.attemptResize(
            QgsLayoutSize(2.8, 2.2, QgsUnitTypes.LayoutCentimeters))
        multiframe2.addFrame(frame2)

        uuids = {
            item1.uuid(),
            item2.uuid(),
            frame1.uuid(),
            frame2.uuid(),
            multiframe1.uuid(),
            multiframe2.uuid()
        }
        original_uuids = {
            item1.uuid(),
            item2.uuid(),
            frame1.uuid(),
            frame2.uuid()
        }

        self.assertTrue(l.saveAsTemplate(tmpfile, QgsReadWriteContext()))

        l2 = QgsLayout(p)
        with open(tmpfile) as f:
            template_content = f.read()
        doc = QDomDocument()
        doc.setContent(template_content)

        # adding to existing items
        new_items, ok = l2.loadFromTemplate(doc, QgsReadWriteContext(), False)
        self.assertTrue(ok)
        self.assertEqual(len(new_items), 4)
        items = l2.items()
        multiframes = l2.multiFrames()
        self.assertEqual(len(multiframes), 2)
        self.assertTrue([i for i in items if i.id() == 'xxyyxx'])
        self.assertTrue([i for i in items if i.id() == 'zzyyzz'])
        self.assertTrue([i for i in items if i.id() == 'frame1'])
        self.assertTrue([i for i in items if i.id() == 'frame2'])
        self.assertTrue([i for i in multiframes if i.html() == 'mf1'])
        self.assertTrue([i for i in multiframes if i.html() == 'mf2'])
        self.assertTrue(new_items[0] in l2.items())
        self.assertTrue(new_items[1] in l2.items())
        self.assertTrue(new_items[2] in l2.items())
        self.assertTrue(new_items[3] in l2.items())

        # double check that new items have a unique uid
        self.assertNotIn(new_items[0].uuid(), uuids)
        uuids.add(new_items[0].uuid())
        self.assertNotIn(new_items[1].uuid(), uuids)
        uuids.add(new_items[1].uuid())
        self.assertNotIn(new_items[2].uuid(), uuids)
        uuids.add(new_items[2].uuid())
        self.assertNotIn(new_items[3].uuid(), uuids)
        uuids.add(new_items[3].uuid())

        self.assertNotIn(
            multiframes[0].uuid(),
            [multiframe1.uuid(), multiframe2.uuid()])
        self.assertNotIn(
            multiframes[1].uuid(),
            [multiframe1.uuid(), multiframe2.uuid()])
        new_multiframe1 = [i for i in multiframes if i.html() == 'mf1'][0]
        self.assertEqual(new_multiframe1.layout(), l2)
        new_multiframe2 = [i for i in multiframes if i.html() == 'mf2'][0]
        self.assertEqual(new_multiframe2.layout(), l2)
        new_frame1 = sip.cast([i for i in items if i.id() == 'frame1'][0],
                              QgsLayoutFrame)
        new_frame2 = sip.cast([i for i in items if i.id() == 'frame2'][0],
                              QgsLayoutFrame)
        self.assertEqual(new_frame1.multiFrame(), new_multiframe1)
        self.assertEqual(new_multiframe1.frames()[0].uuid(), new_frame1.uuid())
        self.assertEqual(new_frame2.multiFrame(), new_multiframe2)
        self.assertEqual(new_multiframe2.frames()[0].uuid(), new_frame2.uuid())

        # adding to existing items
        new_items2, ok = l2.loadFromTemplate(doc, QgsReadWriteContext(), False)
        self.assertTrue(ok)
        self.assertEqual(len(new_items2), 4)
        items = l2.items()
        self.assertEqual(len(items), 8)
        multiframes2 = l2.multiFrames()
        self.assertEqual(len(multiframes2), 4)
        multiframes2 = [
            m for m in l2.multiFrames() if
            not m.uuid() in [new_multiframe1.uuid(),
                             new_multiframe2.uuid()]
        ]
        self.assertEqual(len(multiframes2), 2)
        self.assertTrue([i for i in items if i.id() == 'xxyyxx'])
        self.assertTrue([i for i in items if i.id() == 'zzyyzz'])
        self.assertTrue([i for i in items if i.id() == 'frame1'])
        self.assertTrue([i for i in items if i.id() == 'frame2'])
        self.assertTrue([i for i in multiframes2 if i.html() == 'mf1'])
        self.assertTrue([i for i in multiframes2 if i.html() == 'mf2'])
        self.assertTrue(new_items[0] in l2.items())
        self.assertTrue(new_items[1] in l2.items())
        self.assertTrue(new_items[2] in l2.items())
        self.assertTrue(new_items[3] in l2.items())
        self.assertTrue(new_items2[0] in l2.items())
        self.assertTrue(new_items2[1] in l2.items())
        self.assertTrue(new_items2[2] in l2.items())
        self.assertTrue(new_items2[3] in l2.items())
        self.assertNotIn(new_items2[0].uuid(), uuids)
        uuids.add(new_items[0].uuid())
        self.assertNotIn(new_items2[1].uuid(), uuids)
        uuids.add(new_items[1].uuid())
        self.assertNotIn(new_items2[2].uuid(), uuids)
        uuids.add(new_items[2].uuid())
        self.assertNotIn(new_items2[3].uuid(), uuids)
        uuids.add(new_items[3].uuid())

        self.assertNotIn(multiframes2[0].uuid(), [
            multiframe1.uuid(),
            multiframe2.uuid(),
            new_multiframe1.uuid(),
            new_multiframe2.uuid()
        ])
        self.assertNotIn(multiframes2[1].uuid(), [
            multiframe1.uuid(),
            multiframe2.uuid(),
            new_multiframe1.uuid(),
            new_multiframe2.uuid()
        ])

        new_multiframe1b = [i for i in multiframes2 if i.html() == 'mf1'][0]
        self.assertEqual(new_multiframe1b.layout(), l2)
        new_multiframe2b = [i for i in multiframes2 if i.html() == 'mf2'][0]
        self.assertEqual(new_multiframe2b.layout(), l2)
        new_frame1b = sip.cast([
            i for i in items
            if i.id() == 'frame1' and i.uuid() != new_frame1.uuid()
        ][0], QgsLayoutFrame)
        new_frame2b = sip.cast([
            i for i in items
            if i.id() == 'frame2' and i.uuid() != new_frame2.uuid()
        ][0], QgsLayoutFrame)
        self.assertEqual(new_frame1b.multiFrame(), new_multiframe1b)
        self.assertEqual(new_multiframe1b.frames()[0].uuid(),
                         new_frame1b.uuid())
        self.assertEqual(new_frame2b.multiFrame(), new_multiframe2b)
        self.assertEqual(new_multiframe2b.frames()[0].uuid(),
                         new_frame2b.uuid())

        # clearing existing items
        new_items3, ok = l2.loadFromTemplate(doc, QgsReadWriteContext(), True)
        new_multiframes = l2.multiFrames()
        self.assertTrue(ok)
        self.assertEqual(len(new_items3), 5)  # includes page
        self.assertEqual(len(new_multiframes), 2)
        items = l2.items()
        self.assertTrue([
            i for i in items
            if isinstance(i, QgsLayoutItem) and i.id() == 'xxyyxx'
        ])
        self.assertTrue([
            i for i in items
            if isinstance(i, QgsLayoutItem) and i.id() == 'zzyyzz'
        ])
        self.assertTrue([
            i for i in items
            if isinstance(i, QgsLayoutItem) and i.id() == 'frame1'
        ])
        self.assertTrue([
            i for i in items
            if isinstance(i, QgsLayoutItem) and i.id() == 'frame2'
        ])
        self.assertTrue(new_items3[0] in l2.items())
        self.assertTrue(new_items3[1] in l2.items())
        self.assertTrue(new_items3[2] in l2.items())
        self.assertTrue(new_items3[3] in l2.items())
        new_multiframe1 = [i for i in new_multiframes if i.html() == 'mf1'][0]
        new_multiframe2 = [i for i in new_multiframes if i.html() == 'mf2'][0]

        new_frame1 = sip.cast([
            i for i in items
            if isinstance(i, QgsLayoutItem) and i.id() == 'frame1'
        ][0], QgsLayoutFrame)
        new_frame2 = sip.cast([
            i for i in items
            if isinstance(i, QgsLayoutItem) and i.id() == 'frame2'
        ][0], QgsLayoutFrame)
        self.assertEqual(new_frame1.multiFrame(), new_multiframe1)
        self.assertEqual(new_multiframe1.frames()[0].uuid(), new_frame1.uuid())
        self.assertEqual(new_frame2.multiFrame(), new_multiframe2)
        self.assertEqual(new_multiframe2.frames()[0].uuid(), new_frame2.uuid())
Exemplo n.º 4
0
    def testSaveLoadTemplate(self):
        tmpfile = os.path.join(self.basetestpath, 'testTemplate.qpt')

        p = QgsProject()
        l = QgsLayout(p)
        l.initializeDefaults()

        # add some items
        item1 = QgsLayoutItemLabel(l)
        item1.setId('xxyyxx')
        item1.attemptMove(QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters))
        item1.attemptResize(QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        l.addItem(item1)
        item2 = QgsLayoutItemLabel(l)
        item2.setId('zzyyzz')
        item2.attemptMove(QgsLayoutPoint(1.4, 1.8, QgsUnitTypes.LayoutCentimeters))
        item2.attemptResize(QgsLayoutSize(2.8, 2.2, QgsUnitTypes.LayoutCentimeters))
        l.addItem(item2)

        uuids = {item1.uuid(), item2.uuid()}
        original_uuids = {item1.uuid(), item2.uuid()}

        self.assertTrue(l.saveAsTemplate(tmpfile, QgsReadWriteContext()))

        l2 = QgsLayout(p)
        with open(tmpfile) as f:
            template_content = f.read()
        doc = QDomDocument()
        doc.setContent(template_content)

        # adding to existing items
        new_items, ok = l2.loadFromTemplate(doc, QgsReadWriteContext(), False)
        self.assertTrue(ok)
        self.assertEqual(len(new_items), 2)
        items = l2.items()
        self.assertTrue([i for i in items if i.id() == 'xxyyxx'])
        self.assertTrue([i for i in items if i.id() == 'zzyyzz'])
        self.assertTrue(new_items[0] in l2.items())
        self.assertTrue(new_items[1] in l2.items())
        # double check that new items have a unique uid
        self.assertNotIn(new_items[0].uuid(), uuids)
        self.assertIn(new_items[0].templateUuid(), original_uuids)
        uuids.add(new_items[0].uuid())
        self.assertNotIn(new_items[1].uuid(), uuids)
        self.assertIn(new_items[1].templateUuid(), original_uuids)
        uuids.add(new_items[1].uuid())

        # adding to existing items
        new_items2, ok = l2.loadFromTemplate(doc, QgsReadWriteContext(), False)
        self.assertTrue(ok)
        self.assertEqual(len(new_items2), 2)
        items = l2.items()
        self.assertEqual(len(items), 4)
        self.assertTrue([i for i in items if i.id() == 'xxyyxx'])
        self.assertTrue([i for i in items if i.id() == 'zzyyzz'])
        self.assertTrue(new_items[0] in l2.items())
        self.assertTrue(new_items[1] in l2.items())
        self.assertTrue(new_items2[0] in l2.items())
        self.assertTrue(new_items2[1] in l2.items())
        self.assertNotIn(new_items2[0].uuid(), uuids)
        self.assertIn(new_items2[0].templateUuid(), original_uuids)
        uuids.add(new_items[0].uuid())
        self.assertNotIn(new_items2[1].uuid(), uuids)
        self.assertIn(new_items2[1].templateUuid(), original_uuids)
        uuids.add(new_items[1].uuid())

        # clearing existing items
        new_items3, ok = l2.loadFromTemplate(doc, QgsReadWriteContext(), True)
        self.assertTrue(ok)
        self.assertEqual(len(new_items3), 3) # includes page
        items = l2.items()
        self.assertTrue([i for i in items if isinstance(i, QgsLayoutItem) and i.id() == 'xxyyxx'])
        self.assertTrue([i for i in items if isinstance(i, QgsLayoutItem) and i.id() == 'zzyyzz'])
        self.assertTrue(new_items3[0] in l2.items())
        self.assertTrue(new_items3[1] in l2.items())
        self.assertIn(new_items3[0].templateUuid(), original_uuids)
        self.assertIn(new_items3[1].templateUuid(), original_uuids)
        self.assertEqual(l2.itemByUuid(new_items3[0].templateUuid(), True), new_items3[0])
        self.assertEqual(l2.itemByUuid(new_items3[1].templateUuid(), True), new_items3[1])
Exemplo n.º 5
0
    def testSaveLoadTemplate(self):
        tmpfile = os.path.join(self.basetestpath, 'testTemplate.qpt')

        p = QgsProject()
        l = QgsLayout(p)
        l.initializeDefaults()

        # add some items
        item1 = QgsLayoutItemLabel(l)
        item1.setId('xxyyxx')
        item1.attemptMove(QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters))
        item1.attemptResize(
            QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters))
        l.addItem(item1)
        item2 = QgsLayoutItemLabel(l)
        item2.setId('zzyyzz')
        item2.attemptMove(
            QgsLayoutPoint(1.4, 1.8, QgsUnitTypes.LayoutCentimeters))
        item2.attemptResize(
            QgsLayoutSize(2.8, 2.2, QgsUnitTypes.LayoutCentimeters))
        l.addItem(item2)

        uuids = {item1.uuid(), item2.uuid()}
        original_uuids = {item1.uuid(), item2.uuid()}

        self.assertTrue(l.saveAsTemplate(tmpfile, QgsReadWriteContext()))

        l2 = QgsLayout(p)
        with open(tmpfile) as f:
            template_content = f.read()
        doc = QDomDocument()
        doc.setContent(template_content)

        # adding to existing items
        new_items, ok = l2.loadFromTemplate(doc, QgsReadWriteContext(), False)
        self.assertTrue(ok)
        self.assertEqual(len(new_items), 2)
        items = l2.items()
        self.assertTrue([i for i in items if i.id() == 'xxyyxx'])
        self.assertTrue([i for i in items if i.id() == 'zzyyzz'])
        self.assertTrue(new_items[0] in l2.items())
        self.assertTrue(new_items[1] in l2.items())
        # double check that new items have a unique uid
        self.assertNotIn(new_items[0].uuid(), uuids)
        self.assertIn(new_items[0].templateUuid(), original_uuids)
        uuids.add(new_items[0].uuid())
        self.assertNotIn(new_items[1].uuid(), uuids)
        self.assertIn(new_items[1].templateUuid(), original_uuids)
        uuids.add(new_items[1].uuid())

        # adding to existing items
        new_items2, ok = l2.loadFromTemplate(doc, QgsReadWriteContext(), False)
        self.assertTrue(ok)
        self.assertEqual(len(new_items2), 2)
        items = l2.items()
        self.assertEqual(len(items), 4)
        self.assertTrue([i for i in items if i.id() == 'xxyyxx'])
        self.assertTrue([i for i in items if i.id() == 'zzyyzz'])
        self.assertTrue(new_items[0] in l2.items())
        self.assertTrue(new_items[1] in l2.items())
        self.assertTrue(new_items2[0] in l2.items())
        self.assertTrue(new_items2[1] in l2.items())
        self.assertNotIn(new_items2[0].uuid(), uuids)
        self.assertIn(new_items2[0].templateUuid(), original_uuids)
        uuids.add(new_items[0].uuid())
        self.assertNotIn(new_items2[1].uuid(), uuids)
        self.assertIn(new_items2[1].templateUuid(), original_uuids)
        uuids.add(new_items[1].uuid())

        # clearing existing items
        new_items3, ok = l2.loadFromTemplate(doc, QgsReadWriteContext(), True)
        self.assertTrue(ok)
        self.assertEqual(len(new_items3), 3)  # includes page
        items = l2.items()
        self.assertTrue([
            i for i in items
            if isinstance(i, QgsLayoutItem) and i.id() == 'xxyyxx'
        ])
        self.assertTrue([
            i for i in items
            if isinstance(i, QgsLayoutItem) and i.id() == 'zzyyzz'
        ])
        self.assertTrue(new_items3[0] in l2.items())
        self.assertTrue(new_items3[1] in l2.items())
        self.assertIn(new_items3[0].templateUuid(), original_uuids)
        self.assertIn(new_items3[1].templateUuid(), original_uuids)
        self.assertEqual(l2.itemByUuid(new_items3[0].templateUuid(), True),
                         new_items3[0])
        self.assertEqual(l2.itemByUuid(new_items3[1].templateUuid(), True),
                         new_items3[1])
Exemplo n.º 6
0
def makeAtlas(qptChapter,
              qptDivision,
              qptForm,
              zl_layer,
              zl_field,
              di_layer,
              di_field,
              di_name,
              scale,
              form_file=None,
              form=False,
              project_name='',
              root_out='',
              pbar=False,
              isTest=True):

    root_code = os.path.dirname(os.path.realpath(__file__))

    ## getpapersize
    template_file = open(qptDivision, 'r')
    template_content = template_file.read()
    template_file.close()
    document = QDomDocument()
    document.setContent(template_content)
    p = QgsProject().instance()
    composition = QgsLayout(p)
    composition.loadFromTemplate(document, QgsReadWriteContext())
    map_item = composition.itemById('mapa')
    paper = [
        map_item.sizeWithUnits().width(),
        map_item.sizeWithUnits().height()
    ]

    ##get visible layers
    visibleLayers = p.mapThemeCollection().masterVisibleLayers()

    ## get project srid...
    crs = zl_layer.dataProvider().sourceCrs().authid()

    ## zones 1 layer
    zvl = zl_layer.clone()
    global ZVL
    ZVL = zvl.id()
    QgsProject.instance().addMapLayer(zvl)
    #pr = zvl.dataProvider()
    QgsProject.instance().mapLayer(ZVL).loadNamedStyle(
        root_code + '/templates/layerstyles/zones.qml')

    ## divisions 1 layer
    dvl = QgsVectorLayer("Polygon?crs=" + crs, "divisions_layer", "memory")
    global DVL
    DVL = dvl.id()
    QgsProject.instance().addMapLayer(dvl)
    #pr = dvl.dataProvider()
    QgsProject.instance().mapLayer(DVL).startEditing()
    QgsProject.instance().mapLayer(DVL).loadNamedStyle(
        root_code + '/templates/layerstyles/div1.qml')

    pr_dvl = QgsProject.instance().mapLayer(DVL).dataProvider()
    pr_dvl.addAttributes([
        QgsField('id', QVariant.String),
        QgsField('name', QVariant.String),
        QgsField('ang', QVariant.String),
        QgsField('x', QVariant.String),
        QgsField('y', QVariant.String),
    ])

    QgsProject.instance().mapLayer(DVL).commitChanges()

    ## divisions 2 layer
    dvl2 = QgsVectorLayer("Polygon?crs=" + crs, "divisions_layer", "memory")
    global DVL2
    DVL2 = dvl2.id()
    QgsProject.instance().addMapLayer(dvl2)
    #pr = dvl2.dataProvider()
    QgsProject.instance().mapLayer(DVL2).startEditing()
    QgsProject.instance().mapLayer(DVL2).loadNamedStyle(
        root_code + '/templates/layerstyles/div2.qml')
    pr_dvl2 = QgsProject.instance().mapLayer(DVL2).dataProvider()
    pr_dvl2.addAttributes([
        QgsField('id', QVariant.String),
        QgsField('name', QVariant.String),
        QgsField('ang', QVariant.String),
        QgsField('x', QVariant.String),
        QgsField('y', QVariant.String),
    ])
    QgsProject.instance().mapLayer(DVL2).commitChanges()

    debug('>> layers setted')

    ##makestyles::
    p = QgsProject.instance()

    #_zona_big
    p.mapThemeCollection().removeMapTheme('_zona_big')
    rec = QgsMapThemeCollection().MapThemeRecord()
    recList = []
    vl = visibleLayers
    for v in vl:
        recList.append(QgsMapThemeCollection().MapThemeLayerRecord(v))
    recList.append(QgsMapThemeCollection().MapThemeLayerRecord(zvl))
    recList.append(QgsMapThemeCollection().MapThemeLayerRecord(dvl))
    recList.append(QgsMapThemeCollection().MapThemeLayerRecord(dvl2))
    rec.setLayerRecords(recList)
    p.mapThemeCollection().insert('_zona_big', rec)

    #_zona_small
    p.mapThemeCollection().removeMapTheme('_zona_small')
    rec = QgsMapThemeCollection().MapThemeRecord()
    recList = []
    vl = visibleLayers
    for v in vl:
        recList.append(QgsMapThemeCollection().MapThemeLayerRecord(v))
    if di_layer not in vl:
        recList.append(QgsMapThemeCollection().MapThemeLayerRecord(di_layer))
    recList.append(QgsMapThemeCollection().MapThemeLayerRecord(zvl))
    rec.setLayerRecords(recList)
    p.mapThemeCollection().insert('_zona_small', rec)

    #_szona_big
    p.mapThemeCollection().removeMapTheme('_szona_big')
    rec = QgsMapThemeCollection().MapThemeRecord()
    recList = []
    vl = visibleLayers
    for v in vl:
        recList.append(QgsMapThemeCollection().MapThemeLayerRecord(v))
    if di_layer not in vl:
        recList.append(QgsMapThemeCollection().MapThemeLayerRecord(di_layer))
    recList.append(QgsMapThemeCollection().MapThemeLayerRecord(zvl))
    rec.setLayerRecords(recList)
    p.mapThemeCollection().insert('_szona_big', rec)

    #_szona_small
    p.mapThemeCollection().removeMapTheme('_szona_small')
    rec = QgsMapThemeCollection().MapThemeRecord()
    recList = []
    vl = visibleLayers
    for v in vl:
        recList.append(QgsMapThemeCollection().MapThemeLayerRecord(v))
    if di_layer not in vl:
        recList.append(QgsMapThemeCollection().MapThemeLayerRecord(di_layer))
    recList.append(QgsMapThemeCollection().MapThemeLayerRecord(zvl))
    recList.append(QgsMapThemeCollection().MapThemeLayerRecord(dvl))
    recList.append(QgsMapThemeCollection().MapThemeLayerRecord(dvl2))
    rec.setLayerRecords(recList)
    p.mapThemeCollection().insert('_szona_small', rec)

    global mapL
    mapLmake()

    ##se puede agilizar
    #Lz = zl_layer #QgsProject.instance().mapLayer(mapL['zones'])

    #Lb = QgsProject.instance().mapLayer(mapL['bounds'])
    #Ld = QgsProject.instance().mapLayer(mapL['divisions'])

    ###########################################################################

    x = 0
    global pag
    pag = 1
    #for b in Lb.getFeatures():
    fr = 0
    zones_f = [zzz for zzz in zl_layer.getFeatures()]
    if pbar:
        pbar.setValue(1)
    for b in zones_f:
        if pbar:
            pbar.setValue(100 / len(zones_f) * fr)
        fr += 1
        debug('>>>> chapter: ')
        debug(b.attributes())

        #isTest
        #self.dlg.progressBar.setValue(int(10))
        szs = getSubzones(b, paper, scale)
        mkChapter(b, qptChapter, project_name, root_out, zl_layer, zl_field,
                  di_layer, di_field, di_name)
        szfr = 0
        for sz in szs:
            szfr += 1
            if pbar:
                pbar.setValue(100 / len(zones_f) * fr +
                              100 / len(zones_f) / len(szs) * szfr)
            debug('>>>> division: ')
            mkDiv(sz, b.geometry(), qptDivision, project_name, root_out,
                  zl_layer, zl_field, di_layer, di_field, di_name)
            if form:
                mkForm(sz, qptForm, form_file, project_name, root_out,
                       zl_layer, zl_field, di_layer, di_field, di_name)
            if isTest:
                break
        if isTest:
            break
        x += 1

    #emptyTemp()

    # #remove styles
    p.mapThemeCollection().removeMapTheme('_zona_big')
    p.mapThemeCollection().removeMapTheme('_zona_small')
    p.mapThemeCollection().removeMapTheme('_szona_big')
    p.mapThemeCollection().removeMapTheme('_szona_small')

    #remove layers
    QgsProject.instance().removeMapLayer(ZVL)
    QgsProject.instance().removeMapLayer(DVL)
    QgsProject.instance().removeMapLayer(DVL2)

    debug('end')

    return
Exemplo n.º 7
0
def mkForm(b, qptForm, form_file, project_name, root_out, zl_layer, zl_field,
           di_layer, di_field, di_name):
    root_code = os.path.dirname(os.path.realpath(__file__))
    name = str(b.attribute(1).replace('_', '.')) + '_' + str(
        b.attribute(3)) + '_' + str(b.attribute(4))

    template_file = open(qptForm, 'r')
    template_content = template_file.read()
    template_file.close()
    document = QDomDocument()
    document.setContent(template_content)

    composition = QgsLayout(QgsProject().instance())
    composition.loadFromTemplate(document, QgsReadWriteContext())

    corners = composition.itemById('corners')
    corners.setPicturePath(root_code + '/templates/corners_a4.svg')

    logo = composition.itemById('logo')
    logo.setPicturePath(root_code + '/templates/logo.svg')

    ##title
    ti = composition.itemById('project')
    ti.setText(project_name)

    ##zona
    zo = composition.itemById('zona')
    zo.setText(str(b.attribute(1).replace('_', '.')))

    ##pagina
    zo = composition.itemById('pagina')
    zo.setText(name)

    #form
    qr = composition.itemById('form')
    qr.setPicturePath(form_file)

    #qrcode
    qr = composition.itemById('qrcode')
    data = name
    qrpath = makeQR(data, name)
    qr.setPicturePath(qrpath)

    ##cbarres
    cbarres = composition.itemById('cbarres')
    cbarres.setText('*' + str(b.attribute(1).replace('_', '.')) + ',' +
                    str(b.attribute(3)) + ',' + str(b.attribute(4)) + '*')

    composition.refresh()

    zz = zl_layer.getFeatures(
        QgsFeatureRequest(QgsExpression('"name" = \'' + b.attribute(1) +
                                        '\'')))
    zz = [x for x in zz]
    z = zz[0].geometry()
    currentDistrict = unicode(zz[0].attribute(zl_field))

    image_name = str(b.attribute(1).replace('_', '-')) + '_' + str(
        b.id()) + '_form' + '_' + currentDistrict
    printRaster(composition, image_name, root_out)
    return
Exemplo n.º 8
0
def mkDiv(b, z, qptDivision, project_name, root_out, zl_layer, zl_field,
          di_layer, di_field, di_name):

    root_code = os.path.dirname(os.path.realpath(__file__))
    Lz = zl_layer  #QgsProject.instance().mapLayer(mapL['zones'])
    debug(b.attributes())
    #angle = b.attribute('ang')
    angle = b.attribute(2)
    #esto visulamente es correcto
    ##pero me fastidia la lectira posterior porque no dejo rastro de esta manipulacion
    ##para el escaneo posterio deberia de modificar el orden de los bounds en el qr y en el pie de pagina

    if angle > 45:
        angle = angle - 90
    elif angle < -45:
        angle = angle + 90

    # sql = '"name" = \''+b.attribute('name')+'\''
    # sql += ' AND "x" = '+str(b.attribute('x'))
    # sql += ' AND "y" = '+str(b.attribute('y'))
    #filter('divisions', sql)

    sql = '"name" = \'' + b.attribute(1) + '\''
    sql += ' AND "x" = ' + str(b.attribute(3))
    sql += ' AND "y" = ' + str(b.attribute(4))

    QgsProject.instance().mapLayer(DVL).setSubsetString(sql)

    sql2 = '"name" = \'' + b.attribute(1) + '\''
    #sql2 = '"name" = \'' + b.attribute('name') + '\''
    #filter('divisions2', sql2)
    QgsProject.instance().mapLayer(DVL2).setSubsetString(sql)

    template_file = open(qptDivision, 'r')
    template_content = template_file.read()
    template_file.close()
    document = QDomDocument()
    document.setContent(template_content)

    p = QgsProject().instance()
    composition = QgsLayout(p)
    composition.loadFromTemplate(document, QgsReadWriteContext())

    ##mapa principal
    map_item = composition.itemById('mapa')
    map_item.setKeepLayerStyles(True)
    map_item.setKeepLayerSet(True)
    map_item.setFollowVisibilityPreset(True)
    map_item.setFollowVisibilityPresetName('_szona_big')

    map_item.setMapRotation(-angle)  ########
    cc = b.geometry().centroid().asPoint()
    coordsDesc = str(b.geometry().asWkt())[10:][:-2].split(', ')

    b.geometry().rotate(-angle, cc)
    rBound = b.geometry().boundingBox()
    map_item.zoomToExtent(rBound)

    ##mapa 2
    map_item2 = composition.itemById('minimapa')
    map_item2.setKeepLayerStyles(True)
    map_item2.setKeepLayerSet(True)
    map_item2.setFollowVisibilityPreset(True)
    map_item2.setFollowVisibilityPresetName('_szona_small')

    #cuidado que aqu´i se lia con valor integer o string
    zz = zl_layer.getFeatures(
        QgsFeatureRequest(QgsExpression('"name" = \'' + b.attribute(1) +
                                        '\'')))
    zz = [x for x in zz]
    z = zz[0].geometry()
    map_item2.zoomToExtent(z.boundingBox())

    ##barrio y distrito
    distrito = composition.itemById('distrito')
    distrito.setText('districte : ' + unicode(zz[0].attribute('d_name')))

    barrio = composition.itemById('barrio')

    fields = [e.name() for e in zz[0].fields().toList()]
    if 'b_name' in fields:
        barrio.setText('barri : ' + zz[0].attribute('b_name'))
    else:
        barrio.setText('zona : ' + zz[0].attribute('name').replace('_', '.'))

    ##anotacion coordenadas
    coordsDesc = [c.split(' ') for c in coordsDesc]

    coords = composition.itemById('coordenadas')
    coords.setText(' aX: '+str(round(float(coordsDesc[0][0]),0))+ \
                   ' ay: '+str(round(float(coordsDesc[0][1]),0))+ \
                   ' bX: '+str(round(float(coordsDesc[1][0]),0))+ \
                   ' by: '+str(round(float(coordsDesc[1][1]),0))+ \
                   ' cX: '+str(round(float(coordsDesc[2][0]),0))+ \
                   ' cy: '+str(round(float(coordsDesc[2][1]),0))+ \
                   ' dX: '+str(round(float(coordsDesc[3][0]),0))+ \
                   ' dy: '+str(round(float(coordsDesc[3][1]),0))
                   )

    ##zona
    zo = composition.itemById('zona')
    zo.setText(str(b.attribute(1).replace('_', '.')))

    ##title
    ti = composition.itemById('project')
    ti.setText(project_name)

    ##cbarres
    #cb_name = 'cb_'+str(b.attribute('name').replace('_', '.'))+'_'+str(b.attribute('x'))+'_'+str(b.attribute('y'))
    cb_text = '*' + str(b.attribute(1).replace('_', '.')) + ',' + str(
        b.attribute(3)) + ',' + str(b.attribute(4)) + '*'
    #makeBarcode(cb_text, cb_name)

    cbarres = composition.itemById('cbarres')
    cbarres.setText(cb_text)

    #qrcode
    name = str(b.attribute(1).replace('_', '.')) + '_' + str(
        b.attribute(3)) + '_' + str(b.attribute(4))
    qr = composition.itemById('qrcode')
    data =  name+' '+ \
            str(round(float(coordsDesc[0][0]),3))+' '+ \
            str(round(float(coordsDesc[0][1]),3))+', '+ \
            str(round(float(coordsDesc[1][0]),3))+' '+ \
            str(round(float(coordsDesc[1][1]),3))+', '+ \
            str(round(float(coordsDesc[2][0]),3))+' '+ \
            str(round(float(coordsDesc[2][1]),3))+', '+ \
            str(round(float(coordsDesc[3][0]),3))+' '+ \
            str(round(float(coordsDesc[3][1]),3))

    qrpath = makeQR(data, name)
    qr.setPicturePath(qrpath)

    #pagina
    pagina = composition.itemById('pagina')
    pagina.setText(name)

    #norte
    corners = composition.itemById('corners')
    corners.setPicturePath(root_code + '/templates/corners_a4.svg')

    logo = composition.itemById('logo')
    logo.setPicturePath(root_code + '/templates/logo.svg')

    norte = composition.itemById('norte')
    norte.setPicturePath(root_code + '/templates/norte.svg')
    norte.setRotation(angle)

    composition.refresh()
    currentDistrict = unicode(zz[0].attribute(zl_field))
    image_name = str(b.attribute(1).replace('_', '-')) + '_' + str(
        b.id()) + '_' + currentDistrict
    printRaster(composition, image_name, root_out)
    return
Exemplo n.º 9
0
def mkChapter(b, qptChapter, project_name, root_out, zl_layer, zl_field,
              di_layer, di_field, di_name):
    """
    b es un bound
    """
    root_code = os.path.dirname(os.path.realpath(__file__))
    Lz = zl_layer  #QgsProject.instance().mapLayer(mapL['zones'])

    file_qptChapter = open(qptChapter, 'r')
    template_content_chapter = file_qptChapter.read()
    file_qptChapter.close()

    ###
    #filter('zones', '"name" = \''+b.attribute('name')+'\'' )#cuidado si el valor es integer o string
    #filter('zones2', '"name" = \''+b.attribute('name')+'\'' )#cuidado si el valor es integer o string
    #filter('divisions', '"name" = \''+b.attribute('name')+'\'' )
    #filter('divisions2', '"name" = \'' + b.attribute('name') + '\'')

    # QgsProject.instance().mapLayer(ZVL).setSubsetString( '"name" = \''+b.attribute('name')+'\'' )
    # QgsProject.instance().mapLayer(DVL).setSubsetString('"name" = \''+b.attribute('name')+'\'' )
    # QgsProject.instance().mapLayer(DVL2).setSubsetString('"name" = \''+b.attribute('name')+'\'' )

    # QgsProject.instance().mapLayer(ZVL).setSubsetString( '"%s" = \'%s\'' %(zl_field, b.attribute(zl_field)) )
    # QgsProject.instance().mapLayer(DVL).setSubsetString('"%s" = \'%s\'' %(di_field, b.attribute(zl_field))  )
    # QgsProject.instance().mapLayer(DVL2).setSubsetString('"%s" = \'%s\'' %(di_field, b.attribute(zl_field)) )

    ### seleccionamos la zona
    #zz = Lz.getFeatures(QgsFeatureRequest(QgsExpression('"name" = \''+b.attribute('name')+'\''))) #cuidado si el valor es integer o string
    print('zz', '"%s" = \'%s\'' % (zl_field, b.attribute(zl_field)))
    zz = Lz.getFeatures(
        QgsFeatureRequest(
            QgsExpression('"%s" = \'%s\'' % (zl_field, b.attribute(zl_field))))
    )  #cuidado si el valor es integer o string

    zz = [x for x in zz]

    # escogemos el distrito correspondiente a la zona
    #filter('districtes', '"name" = \''+unicode(zz[0].attribute('d_name'))+'\'' )
    di_layer.setSubsetString('"' + di_field + '" = \'' +
                             unicode(zz[0].attribute(zl_field)) + '\'')

    global currentDistrict
    #currentDistrict = unicode(zz[0].attribute('d_id'))
    currentDistrict = unicode(zz[0].attribute(zl_field))

    #coje la geometria del distriro
    #distri = QgsProject.instance().mapLayer(mapL['districtes'])
    gd = [d for d in di_layer.getFeatures()][0]

    #canvas = QgsMapCanvas()
    document = QDomDocument()
    document.setContent(template_content_chapter)

    p = QgsProject().instance()
    composition = QgsLayout(p)
    composition.loadFromTemplate(document, QgsReadWriteContext())

    ##
    bounds = (b.geometry()).boundingBox()

    map_item = composition.itemById('mapa')
    map_item.zoomToExtent(bounds)
    map_item.setKeepLayerStyles(True)
    map_item.setKeepLayerSet(True)
    map_item.setFollowVisibilityPreset(True)
    map_item.setFollowVisibilityPresetName('_zona_big')

    map_item_distri = composition.itemById('mapDistrito')
    map_item_distri.zoomToExtent(gd.geometry().boundingBox())
    map_item_distri.setKeepLayerStyles(True)
    map_item_distri.setKeepLayerSet(True)
    map_item_distri.setFollowVisibilityPreset(True)
    map_item_distri.setFollowVisibilityPresetName('_zona_small')

    ##title
    ti = composition.itemById('project')
    ti.setText(project_name)

    ##zona
    zo = composition.itemById('zona')
    zo.setText(str(b.attribute('id')))

    corners = composition.itemById('corners')
    corners.setPicturePath(root_code + '/templates/corners_a4.svg')

    logo = composition.itemById('logo')
    logo.setPicturePath(root_code + '/templates/logo.svg')

    #norte = composition.itemById('norte')
    #norte.setPicturePath(root_code+'templates/norte.svg')
    #norte.setRotation(angle)

    ##barrio y distrito
    distrito = composition.itemById('distrito')
    distrito.setText('districte : ' + unicode(zz[0].attribute('d_name')))
    barrio = composition.itemById('barrio')
    fields = [e.name() for e in zz[0].fields().toList()]
    if 'b_name' in fields:
        barrio.setText('barri : ' + zz[0].attribute('b_name'))  #legacy
    else:
        barrio.setText('zona : ' + zz[0].attribute('name').replace('_', '.'))

    composition.refresh()
    image_name = str(b.attribute('name').replace('_',
                                                 '-')) + '_' + currentDistrict
    printRaster(composition, image_name, root_out)

    # filter('divisions', '' )
    # filter('divisions2', '' )
    # filter('districtes', '' )

    QgsProject.instance().mapLayer(DVL).setSubsetString('')
    QgsProject.instance().mapLayer(DVL2).setSubsetString('')

    return
Exemplo n.º 10
0
    def exportPDF(self, model, chart_path, gyf, exportDialog, area_id, groups,
                  feature_gids, total):

        # Text from export dialog
        map_title = exportDialog.projectName.text()
        area_name = exportDialog.areaName.text()
        output_path = exportDialog.pdfPath.text()
        output_name = exportDialog.pdfName.text()
        author = exportDialog.author.text()
        gyf_version = model['Version']  #AP 2.0
        date = datetime.datetime.today().strftime('%Y-%m-%d')

        # Get template
        path = os.path.dirname(os.path.realpath(__file__))
        a = path.rfind('\\')
        template_file = open(path[:a] + "/template/qgyf_template1.qpt",
                             encoding="utf-8")
        template_content = template_file.read()
        template_file.close()

        document = QDomDocument()
        proj = QgsProject.instance()
        document.setContent(template_content)
        composition = QgsLayout(proj)
        composition.loadFromTemplate(document, QgsReadWriteContext())

        # Title
        title = sip.cast(composition.itemById("title"), QgsLayoutItemLabel)
        title.setText(map_title)
        title = sip.cast(composition.itemById("title1"), QgsLayoutItemLabel)
        title.setText(map_title)
        title = sip.cast(composition.itemById("title2"), QgsLayoutItemLabel)
        title.setText(map_title)

        # GYF value
        value = sip.cast(composition.itemById("gyf_value"), QgsLayoutItemLabel)
        value.setText('GYF  ' + gyf)
        value = sip.cast(composition.itemById("gyf_value1"),
                         QgsLayoutItemLabel)
        value.setText('GYF  ' + gyf)
        value = sip.cast(composition.itemById("gyf_value2"),
                         QgsLayoutItemLabel)
        value.setText('GYF  ' + gyf)

        # GYF groups
        groups = sorted(list(set(groups)))
        groupList = sip.cast(composition.itemById("groups"),
                             QgsLayoutItemLabel)
        text = '''<font face="tahoma" color="#238973"><h3>GYF Kategorier:</h3></font>
        <p style="font-family:tahoma; font-size:13.5; font-color:#4d4949; line-height:21px">'''
        for g in groups:
            text += g + '<br>'
        text = text + '</p>'
        groupList.setText(text)

        # Research Area
        area_id = area_id.id()
        research_area_lyr = proj.mapLayersByName('Beräkningsområde')[0]
        query = "id = " + str(area_id)
        research_area_lyr.setSubsetString(query)
        for feature in research_area_lyr.getFeatures():
            s = feature['yta']
        area_info = sip.cast(composition.itemById("area_info"),
                             QgsLayoutItemLabel)
        items = [['Beräkningsyta: ', str(int(float(s)))],
                 ['Ekoeffektiv yta: ',
                  str(int(float(total)))]]
        text2 = ""
        for i in items:
            text2 += '<font face="tahoma" color="#238973"><b>'+ i[0] + \
            '</b></font><p style="display:inline;font-family:tahoma; font-size:13.5; font-color:#4d4949; line-height:19px">''' + \
            i[1] + ' m<sup>2</sup></p><br>'
        area_info.setText(text2)
        extent = research_area_lyr.extent()

        # Map
        main_map = sip.cast(composition.itemById("map"), QgsLayoutItemMap)
        main_map.zoomToExtent(extent)
        composition.itemById("map").refresh()
        main_map.setKeepLayerSet(True)
        main_map.setKeepLayerStyles(True)

        # Legend
        legend = sip.cast(composition.itemById("legend"), QgsLayoutItemLegend)
        legend.setLegendFilterByMapEnabled(True)
        # Remove background map from legend - have to be checked out
        #root = QgsLayerTree()
        #for lyr in iface.mapCanvas().layers():
        #    if lyr.type() == QgsMapLayer.VectorLayer:
        #        root.addLayer(lyr)
        #    legend.model().setRootGroup(root)
        legend.setAutoUpdateModel(False)

        # Table Grundytor & Kvaliteter
        root = proj.layerTreeRoot()
        content = [l.name() for l in root.children()]

        db_path = '{}\{}'.format(
            proj.readEntry("QGYF", "dataPath")[0],
            proj.readEntry("QGYF", 'activeDataBase')[0])
        uri = QgsDataSourceUri()
        uri.setDatabase(db_path)
        #Table 2 - ground areas
        uri.setDataSource('', 'ground_areas', None)
        table2 = QgsVectorLayer(uri.uri(), 'ground_areas', 'spatialite')
        if 'ground_areas' not in content:
            proj.addMapLayer(table2, False)
        tableLayout2 = sip.cast(composition.itemById("table2"), QgsLayoutFrame)
        tableLayout2.refreshItemPosition()
        tableLayout2 = tableLayout2.multiFrame()
        tableLayout2.setVectorLayer(table2)
        tableLayout2.setDisplayedFields(
            ['ytgrupp', 'ytklass', 'faktor', 'yta', 'poang'])
        # label
        table_areas = sip.cast(composition.itemById("table_areas"),
                               QgsLayoutItemLabel)
        table2_name = '<font face="tahoma" color="#238973"><b>' + model[
            'Klass_items'][0].title() + 'er</b></font>'
        table_areas.setText(table2_name)
        #h = tableLayout2.totalHeight()

        #Table 1 - qualities
        uri.setDataSource('', 'classification', None)
        table1 = QgsVectorLayer(uri.uri(), 'classification', 'spatialite')
        if 'classification' not in content:
            proj.addMapLayer(table1, False)

        tableLayout = sip.cast(composition.itemById("table"), QgsLayoutFrame)
        #position = tableLayout.positionAtReferencePoint(tableLayout.ReferencePoint())
        #position.setX(position.x() + h)
        #tableLayout.setReferencePoint(position)
        tableLayout.refreshItemPosition()
        tableLayout = tableLayout.multiFrame()
        tableLayout.setVectorLayer(table1)
        tableLayout.setDisplayedFields([
            'id', 'geometri_typ', 'fil_namn', 'grupp', 'kvalitet', 'faktor',
            'yta', 'poang'
        ])
        # Filter
        feature_gids = "', '".join(i for i in feature_gids)
        query = "gid in ('" + feature_gids + "')"
        tableLayout.setFilterFeatures(True)
        tableLayout.setFeatureFilter(query)
        tableLayout.update()
        # label
        table_class = sip.cast(composition.itemById("table_class"),
                               QgsLayoutItemLabel)
        table1_name = '<font face="tahoma" color="#238973"><b>' + model[
            'Klass_items'][1].title() + 'er</b></font>'
        table_class.setText(table1_name)

        # Diagram
        chart = sip.cast(composition.itemById("chart"), QgsLayoutItemPicture)
        chart.setPicturePath(chart_path)
        chart.refreshPicture()

        # Diagram
        chart2 = sip.cast(composition.itemById("chart2"), QgsLayoutItemPicture)
        if float(gyf) > 0.0:
            chart2.setPicturePath(
                proj.readEntry("QGYF", "dataPath")[0] + '\PieChart2.png')
            chart2.refreshPicture()

        # Metadata
        text = '<p style="font-family:tahoma; font-size:13.5; font-color:#4d4949; line-height:21px">Område: ' + \
        area_name + '<br>Utförd av: ' + author + '<br>GYF version: ' + gyf_version + '<br>Datum: ' + date + '</p>'
        info = sip.cast(composition.itemById("info"), QgsLayoutItemLabel)
        info.setText(text)
        info = sip.cast(composition.itemById("info1"), QgsLayoutItemLabel)
        info.setText(text)

        # EXPORT!
        QgsLayoutExporter(composition).exportToPdf(
            output_path + '/' + output_name,
            QgsLayoutExporter.PdfExportSettings())
        QMessageBox.information(ExportDialog(), 'Rapport',
                                'Din rapport har skapats! :)')

        # Reset map view
        research_area_lyr.setSubsetString('')
        proj.removeMapLayer(table1)
        proj.removeMapLayer(table2)