Skip to main content
2 of 2
deleted 15 characters in body
Youssef
  • 385
  • 1
  • 2
  • 10

After some research I made it using standalone script, here is the solution :

import os.path
import sys
#setting the environment variables
os.environ['QGIS_PREFIX_PATH'] = r'C:/OSGeo4W64/apps/qgis'
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = r'C:/OSGEO4~1/apps/Qt5/plugins'
os.environ['PATH'] += r';C:/OSGeo4W64/apps/qgis/bin;C:/OSGeo4W64/apps/Qt5/bin;C:/OSGeo4W64/apps/Python37'
sys.path.extend([r'C:/OSGeo4W64/apps/qgis/python',r'C:/OSGeo4W64/apps/qgis/Python37/Lib/site-packages'])
from qgis.core import *
from PyQt5.QtCore import QRectF

qgs = QgsApplication([], False)
qgs.initQgis()
shp_file = 'path_to_shapfile/file.shp'
vlayer = QgsVectorLayer(shp_file, 'vlayer')
QgsProject.instance().addMapLayer(vlayer,False)

l = QgsPrintLayout(QgsProject.instance())
l.initializeDefaults()
l.setUnits(QgsUnitTypes.LayoutMillimeters)
page = l.pageCollection().pages()[0]  
lm = 20         # left margin
tm = 32         # upper margin
w, h = 900, 600 #width and height

page.setPageSize(QgsLayoutSize(1189, 841)) 
#setting the layer style
blackSymbol = QgsFillSymbol.createSimple({'color': '255,0,0,100',
                                              'color_border': 'BLACK',
                                              'width_border': '0.1'})
vlayer.setRenderer(QgsSingleSymbolRenderer(blackSymbol))
#adding the map to the layout
theMap = QgsLayoutItemMap(l)
theMap.updateBoundingRect()
theMap.setRect(QRectF(lm,tm, w, h)) 
theMap.setPos(lm,tm)
theMap.updateBoundingRect()
theMap.setLayers([vlayer])   
# setting the map extent
theMap.setExtent(QgsRectangle(363600.0, 376800.0, 364500.0 ,377400.0))
theMap.attemptSetSceneRect(QRectF(lm,tm, w, h))
l.addItem(theMap)
l.updateBounds()
#exporting to pdf
exporter =  QgsLayoutExporter(l)
pdf_settings = exporter.PdfExportSettings() 
exporter.exportToPdf('C:/map.pdf', pdf_settings)
qgs.exitQgis()

see : PyQGIS3 developer cookbook

Youssef
  • 385
  • 1
  • 2
  • 10