Creating PDF mapbook document that will contain map for each county in counties feature class using ArcPy?

1374
7
11-04-2018 09:18 AM
Highlighted
New Contributor II

Through a plethora of trials and research, I finally was able to get a script to work.

My original question encompassed me needing to take an .mxd and create a PDF mapbook document that will contain a map for each county in the counties FC. Then, I needed to change the title of each map to the name of the county being shown. Lastly, I need to scale the map a bit so it shows an area just a bit larger than the actual extent.

The following script works great. I hope this will help others in the future;

   
import arcpy, osfrom 
arcpy
.mapping import *

countiesPath
= "C:\\Data\\COUNTIES.shp"
pdfPath = "C:\\Data\\COCounties.pdf"
mxdPath = "C:\\Data\\Counties.mxd"
mxd = MapDocument(mxdPath)

dataFrame
= (mxdPath, "COUNTIES")[0]
listLayers = ListLayers(mxd)

finalPDF
= PDFDocumentCreate(pdfPath)

df
= ListDataFrames(mxd, "Layers")[0]

for layer in listLayers:
    if layer.name == "COUNTIES" :
        with arcpy.da.SearchCursor(layer, "COUNTY") as cursor:
            for row in cursor:
                countyName = row[0]
                whereClause = "COUNTY='"+ countyName + "'"
                arcpy.SelectLayerByAttribute_management(layer, "NEW_SELECTION", whereClause)
                df.zoomToSelectedFeatures()
                arcpy.SelectLayerByAttribute_management(layer,"CLEAR_SELECTION")
                df.scale *= 1.5
                titleItem = ListLayoutElements(mxd, "TEXT_ELEMENT", "title")[0]
                titleItem.text = "Map of: " + countyName + " COUNTY"
                countyPDF=r"C:\\Data"+countyName+".pdf"
                ExportToPDF(mxd,countyPDF,"PAGE_LAYOUT",resolution=600,df_export_width=1100,df_export_height =800)
                finalPDF.appendPages(countyPDF)
                os.remove(countyPDF)

finalPDF
.saveAndClose()
del finalPDF
del mxd
Tags (2)
Reply
0 Kudos
7 Replies
Highlighted
MVP Esteemed Contributor

Sharing with Python‌ since this is more of Python and scripting question than a mapping question.

Your code was/is all strung together.  I took a stab at formatting it using the Syntax highlighter.  Is what I have below correct?  If not, please update your code snippet

# Import all the libraries
import arcpyfrom arcpy.mapping
import *

# Set up variables;
countiesPath = "C:\\Data\\COUNTIES.shp"
pdfPath = "C:\\Data\\Counties.pdf"
mxdPath = "C:\\Data\\Counties.mxd"

#Add a pointer to the counties layer in the data frame
dataFrame = ("COUNTIES")[0]

#Create the master pdf
finalPDF = PDFDocumentCreate("C:\\Data\\CountiesMapbook.pdf")

#Set up cursor for counties (need county name)
#Set up a loop to loop through counties
    # build the where clause
    # select layer by attribute - create a new selection
    # zoom to selelction - set the data frame extent to the getSelectedExtent() of the county layer
    dataFrame.extent = countyLyr.getSelectedExtent()
    # zoom out a bit using the sacale property of the data frame
    # use title property of the map document to change the title of the page
    # export the current map to pdf
    # append the pdf to the master pdf
    finalPDFDoc.append (<temp PDF name is>)
    #delete the map document object, pdf
Highlighted
New Contributor II

Yes,  what you have is correct.  The last line needs to be be indented back though.  Thank you.

Reply
0 Kudos
Highlighted
MVP Regular Contributor

This is what the Data Driven Pages toolbar and tool is designed to do. Enable Data Driven Pages, choose your counties layer, check your layout, and then export to PDF, choosing a single page or a page range.

Creating Data Driven Pages—Help | ArcGIS Desktop 

Regards,

Jim

Reply
0 Kudos
Highlighted
New Contributor II

Jim,

I work with Data Driven Pages quite a bit and understand how they work.  However, what I'm looking for here; is assistance/guidance with Python, Arcpy and working with an .mxd, it's linked data layers and creating a mapbook without any previously setup Data Driven Pages.

Thank you,

Reply
0 Kudos
Highlighted
New Contributor

Data Driven Pages are powerful, but do not always allow the degree of customization needed for a map automation project.  Here is an example of python code we use to automatically generate scores of customized maps within minutes into separate PDF with unique names based on the map layer attributes you select:

import arcpy
import arcpy.mapping
import os
import sys
arcpy.env.workspace = "M:\Maps\Unified"
from arcpy import mapping as MAP
mxd = MAP.MapDocument("M:/Maps/Unified/Unified.mxd")
df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
lyr = arcpy.mapping.ListLayers(mxd, "unified", df)[0]
arcpy.AddMessage(lyr.name)
path = arcpy.env.workspace
print "Program Path: "+path
print "Map Title: "+mxd.title
print "Layer Name: "+lyr.name
#print df.description
fc = "M:\Data\unified\unified.shp"
# rows = arcpy.SearchCursor(fc,("NAME",))
i = 0
while i < 98:
    criteria = "FID = "+str(i)
    rows = arcpy.SearchCursor(fc,criteria)
    row = rows.next()
    #entityname = row[0]
    entityname = row.getValue("NAME")
    print entityname
    df.description = entityname
    mxd.title = entityname
    #entityname = str(i)
    filename = path+"\Unified_"+entityname+".pdf"
    arcpy.AddMessage(criteria)
    arcpy.SelectLayerByAttribute_management(lyr,"NEW_SELECTION",criteria)
    df.extent = lyr.getSelectedExtent()
    arcpy.RefreshActiveView()
    df.zoomToSelectedFeatures()
    arcpy.RefreshActiveView()
    arcpy.mapping.ExportToPDF(mxd,filename)
    i += 1
del mxd
Although the code will run if you have the Unified.mxd ArcGIS map project open, it will run much faster if it is closed while you run the script.  If you want to optimize this code even further, you could have python count the number of rows for your loop rather than hard coding 98 as the number of rows.  We don't run this code often, but it works great in creating uniform maps with all our desired features.
Highlighted
New Contributor II

Thank you!  I'll definitely give this a go.

Reply
0 Kudos
Highlighted
New Contributor

Hello, I am trying to do the exact same thing this code is doing. but with arcpy.mp so that it can be done in ArcGIS Pro. I am struggling with some of the new syntax of arcpy.mp compared to arcpy.mapping. Does anyone know how to do this or point me in the direction with documentation on how to create individual PDF's for features in a feature class? 

Reply
0 Kudos