Python code to export layers on Table of contents of mxd to pdf



# Name: layerstopdf.py
# Date: January 15, 2014
# Author: Sarbajit Gurung
# Description: Export each layer from Table of contents in ArcMap to a pdf document
# ---------------------------------------------------------------------------

# Import arcpy module
import arcpy

# if pdfs need dates attached to their names then use it, otherwise it can be excluded
import datetime
today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)

# Define mxd
mxd = arcpy.mapping.MapDocument(r"C:\input\test.mxd")

#set export path to export pdfs
path = r"C:\output\Maps\\"

# turn each layer on and off and export as pdf
for lyr in arcpy.mapping.ListLayers(mxd):
    if lyr.name == "LayerA":
        lyr.visible = True
        arcpy.RefreshTOC()
        arcpy.RefreshActiveView()
        arcpy.mapping.ExportToPDF(mxd, path + "LayerA_" + yesterday.strftime('%d%b%Y') + ".pdf")
        if lyr.name == "LayerA":
            lyr.visible = False
            arcpy.RefreshTOC()
            arcpy.RefreshActiveView()

    if lyr.name == "LayerB":
        lyr.visible = True
        arcpy.RefreshTOC()
        arcpy.RefreshActiveView()
        arcpy.mapping.ExportToPDF(mxd, path + "LayerB_" + yesterday.strftime('%d%b%Y') +".pdf")
        if lyr.name == "LayerB":
            lyr.visible = False
            arcpy.RefreshTOC()
            arcpy.RefreshActiveView()

# so on and so forth for other Layers on your mxd
# you can also store the layer names in an array and create a loop if you have many layers on TOC

# Release mxd
del mxd

1 comments:

Instead of working on each individual layer, you can also create a nested For loop if you have many layers on the mxd:

# Import arcpy module
import arcpy

# if pdfs need dates attached to their names then use it, otherwise it can be excluded
import datetime
today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)

mxd = arcpy.mapping.MapDocument(r"C:\input\test.mxd")

#set export path to export pdfs
path = r"C:\output\Maps\\"

names = ["LayerA", "LayerB", "LayerC"]

# turn each layer on and off and export as pdf
for lyr in arcpy.mapping.ListLayers(mxd):
for name in names:
if lyr.name == name:
lyr.visible = True
arcpy.RefreshTOC()
arcpy.RefreshActiveView()
arcpy.mapping.ExportToPDF(mxd, path + name + " " + yesterday.strftime('%d%b%Y') + ".pdf")
if lyr.name == name:
lyr.visible = False
arcpy.RefreshTOC()
arcpy.RefreshActiveView()
del mxd

Reply

Post a Comment