5

I want to write Python standalone QGIS script to layout export and my code is as follows:

import os
from qgis.core import (
    QgsVectorLayer,QgsProject, QgsWkbTypes,QgsVectorLayerExporter,QgsCoordinateReferenceSystem,QgsProviderRegistry,  QgsGeometry,
    QgsMapSettings,
    QgsPrintLayout,
    QgsMapSettings,
    QgsMapRendererParallelJob,
    QgsLayoutItemLabel,
    QgsLayoutItemLegend,
    QgsLayoutItemMap,
    QgsLayoutItemPolygon,
    QgsLayoutItemScaleBar,
    QgsLayoutExporter,
    QgsLayoutItem,
    QgsLayoutPoint,
    QgsLayoutSize,    
    QgsUnitTypes,    
    QgsFillSymbol,
    QgsLayout
)
qp = QgsProject.instance()
md = qp.metadata()
md.setTitle('proj title')
md.setAuthor('proj author')
#md.setCreationDateTime(QDateTime(QDate(2011, 5, 3), QTime(9, 4, 5), QTimeZone(36000)))
md.setIdentifier('proj identifier')
md.setAbstract('proj abstract')
md.setKeywords({'kw': ['kw1', 'kw2'], 'KWx': ['kw3', 'kw4']})
qp.setMetadata(md)
l = QgsLayout(qp)
l.initializeDefaults()
exporter = QgsLayoutExporter(l)
# setup settings
settings = QgsLayoutExporter.ImageExportSettings()
settings.dpi = 80
rendered_file_path = os.path.join('D:\data', 'test_exporttoimagedpi.png')
result=exporter.exportToPdf('D:\data\TestLayout.pdf', settings)      
print(result)
print(exporter.errorFile())

If I run the above code, Python is stopped automatically without running complete code with the error:

python.exe - Application Error The instruction at 0x00007FFDA8AFCB4C referenced memory at 0x0000000000000008. The memory could not be read. Click on OK to terminate the program

If I run line by line and found that the line l = QgsLayout(qp) causing for the python crashing.

Can you help me to sort out the problem?

2
  • 1
    Not likely to fix your issue, but you really need to use raw strings or forward slashes for paths, i.e r'D:\data' or 'D:/data' or you'll get other errors in future. Such as '\t' is interpreted by python as a tab character...
    – user2856
    Oct 6, 2021 at 7:33
  • even if its is a problem, code is not running upto that line. It is terminating by running the line l=QgsLayout(qp) Oct 6, 2021 at 8:46

1 Answer 1

8

Add two following lines before qp = QgsProject.instance():

qgs = QgsApplication([], False)
qgs.initQgis()

then, add the next line to the end of the script:

qgs.exitQgis()

An additional warning: You should convert ImageExportSettings() into PdfExportSettings() since you export the layout to pdf. Otherwise, you will get this error:

QgsLayoutExporter.exportToPdf(): arguments did not match any overloaded call

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.