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())
result, error = QgsLayoutExporter.exportToPdf(r, "D://test.pdf", settings)
. Is that just my issue? I tried in the python console both in windows and in the Mac