[GIS] Using ArcPy to export multiple layers to .pdfs

arcgis-10.2arcpylayersloop

I have found a solution to the issue below. The problem had to do with coding GetParameterAsText without actually using it as an input in a tool. That was the reason the raster layers wouldn't turn on.


I am fairly new to Python. Here is my question:

I have individual range maps for several hundred invertebrate species, each of which has the same extent. I would like to export these maps to .pdf using Python in ArcGIS 10.2. Each map also needs to have a "Places" and "Rivers" shapefile (these two shapefiles are the same for all of the species).

I have tried modifying the script from Exporting each layer in map to separate image using ArcPy?, but I can't seem to get the range map rasters to show up.

The following script needs work (and I must give credit to Roy, who answered the other post I mentioned), but this is what I have so far:

mxd = arcpy.mapping.MapDocument("CURRENT")  
df = arcpy.mapping.ListDataFrames(mxd, '')[0]

allLayers = arcpy.GetParameterAsText(0) 
lyrList = allLayers.split(";")

PDFPath = arcpy.GetParameterAsText(1)

for lyr in arcpy.mapping.ListLayers(mxd, '', df):
    for layer in lyrList:
        if lyr.name == "Places":
            lyr.visible = True
        if lyr.name == "Rivers":
            lyr.visible = True
        if lyr.name == layer:
            lyr.visible = True
            arcpy.mapping.ExportToPDF(mxd, os.path.join(r"C:\Project_7\Newer_data\Inverts\GO", PDFPath, lyr.name + ".pdf"), resolution=150) #EDIT: This line is working now.
            lyr.visible = False
    arcpy.RefreshActiveView()
    del mxd         

I don't think I have added the loops in the correct place. I need the "Places" and "Rivers" layers displayed on the map every time (i.e., for each range map).

I am unclear how to modify the following to fit my data:

arcpy.mapping.ExportToPNG(mxd, PDFPath+"\\" + lyr.name + ".pdf")

Specifically, what do I replace the "\" with? Do both backslashes need to be there? (i.e., PDFPath+"C:\Project_7\Newer_data\Inverts\GO\)

Also, I have tried just running the following code without the addition of the two shapefiles, but the layers don't seem to turn on.

for lyr in arcpy.mapping.ListLayers(mxd, '', df):
    for layer in lyrList:
        if lyr.name == layer:
            lyr.visible = True
arcpy.RefreshActiveView()

Best Answer

I'm not sure what you're trying to do with the output file name, but constructing it like that will not work - the path needs to start with C:\.

Also, in Python it's good practice to use os.path.join to add paths together, e.g.

import os

...

arcpy.mapping.ExportToPDF(mxd, os.path.join(r"C:\Project_7\Newer_data\Inverts\GO", PDFPath, lyr.name + ".pdf"))

A single '\' in a string is considered an escape character, so you must either add an 'r' before the string so python treats it as a raw string, or use '\\'.