I have a problem with exporting of a QGIS layout by the pyQGIS. I have prepared the qgz project and also the qpt layout.
When I try to export the layout to PDF by QgsLayoutExporter.exportToPdf by calling python via the CMD, the resulting PDF is not prepared correctly (it has no map and scale bar is corrupted).This error is printed to the CMD window:
ERROR 4: `path\to\output\directory\test.pdf' not recognized as a supported file format.
When I copy and paste the same code into the QGIS python console, resulting PDF is prepared correctly.
I tried the solution on Windows 10, QGIS 3.4 / 3.6 and on Ubuntu 18, QGIS 3.6. The behaviour is the same.
What am I doing wrong or is there a bug in the pyQGIS?
Here is my source code:
import sys, os
from qgis.core import *
from qgis.PyQt.QtXml import QDomDocument
from PyQt5.QtCore import *
from PyQt5.QtXml import *
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = r'path\to\Qt5\plugins'
os.environ['PATH'] += r';path\to\apps\qgis\bin;path\to\apps\Qt5\bin'
# supply path to qgis install location
QgsApplication.setPrefixPath(r"path\to\apps\qgis", True)
# create a reference to the QgsApplication
# setting the second argument to True enables the GUI, which we need
# to do since this is a custom application
qgs = QgsApplication([], False)
# load providers
qgs.initQgis()
# Write your code here to load some layers, use processing
# algorithms, etc.
projectInstance = QgsProject.instance()
projectInstance.read(r'path\to\QGIS\project.qgz')
layout = QgsProject.instance().layoutManager().layoutByName("overview")
pdfPath = os.path.join('path\to\output\directory', 'test.pdf')
exporter = QgsLayoutExporter(layout)
imageSettings = QgsLayoutExporter.PdfExportSettings()
imageSettings.dpi = 300
result = exporter.exportToPdf(pdfPath, imageSettings)
print(result)
print(exporter.errorFile())
# When your script is complete, call exitQgis() to remove the
# provider and layer registries from memory
qgs.exitQgis()
This is the output prepared executing the code in the QGIS Python console: