I have a trouble exporting a print layout in QGIS 3.10 to PDF when doing it programmatically. I've created a project with print layout manually and now just want to modify the content of the map with python and then save it as PDF. This is the code I tried for export, everything works just fine except the last line, which does nothing and ends with code 4.

manager = QgsProject.instance().layoutManager()
layout = manager.layoutByName("my_layout")
exporter = QgsLayoutExporter(layout)
filename = "C://layout.pdf"
#so far so good, but this doesnt create the file:
exporter.exportToPdf(filename, QgsLayoutExporter.PdfExportSettings()) 

Any idea what could be wrong? When I run the export of the same layout manually, it works fine.

1 Answer 1


Code 4 means Could not start printing to destination device (Reference). Probably, Windows does not allow you to write files to the root directory.

Make a new directory in C:, then export the layout into it.

filename = "C:/test/layout.pdf"
exporter.exportToPdf(filename, QgsLayoutExporter.PdfExportSettings()) 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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