1

I'm trying to update a QGIS plugin to PyQGIS 3 but I have some troubles to update the code for exporting layout to PDF. The layout derives from a template file. This is the "old" code:

canv = iface.mapCanvas()
rend = canv.mapRenderer()
rect = QgsRectangle(iface.mapCanvas().extent())

qpt = u'D:\\templates\\qvet_h_template.qpt')
ff = open(qpt, 'r')
tmplt = ff.read()
ff.close()
#zoom on the map
tmplt = tmplt.replace("iymin", str(rect.yMinimum()))
tmplt = tmplt.replace("iymax", str(rect.yMaximum()))
tmplt = tmplt.replace("ixmin", str(rect.xMinimum()))
tmplt = tmplt.replace("ixmax", str(rect.xMaximum()))

doc = QDomDocument()
doc.setContent(tmplt)

comp = QgsComposition(rend)
comp.loadFromTemplate(doc)

pdfpath = u"D:\\outputmap2.pdf"
out = comp.exportAsPDF(pdfpath)

As far as i know, it is necessary replace QgsComposition class and its methods (loadFromTemplate() and exportAsPDF()) as they are no longer present in pyqgis-3. I read to use QgsLayout to replace QgsComposition class, I tried to write some code but with failure. A draft of the code is as follows (the first part is the same as the above code):

doc = QDomDocument()
doc.setContent(tmplt)
ele = doc.documentElement()

project = QgsProject.instance()
lay = QgsPrintLayout(project)
lay.addItemsFromXml(ele, doc, QgsReadWriteContext())

exporter = QgsLayoutExporter(layout)
exporter.exportToPdf(u"D:\\TestLayout.pdf", QgsLayoutExporter.PdfExportSettings())
0

Thank to @Fran Raga suggestions I wrote the follow code and it works.

doc = QDomDocument()
doc.setContent(tmplt)

project = QgsProject.instance()
l = QgsLayout(project)
l.initializeDefaults()

items, ok = l.loadFromTemplate(doc, QgsReadWriteContext(), False)

exporter = QgsLayoutExporter(l)
exporter.exportToPdf(u"D:\\TestLayout.pdf", QgsLayoutExporter.PdfExportSettings())

To prevent QGIS crash, the method .initializeDefaults() should be called (ref in QGIS Api)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.