Thursday, 11 February 2016

arcgis desktop - Group and export to pdf based on an attribute field using DDP - Python Script


Using Python, I want to export a map series. Each series needs to be grouped based on an attribute field which is not being used in DDP settings (page num, page index etc...).


For example: my shapefile RoadName.shp has a field called RoadType. Now when I ask my DDP to export maps, it should group diff RoadTypes into one single (multipage) pdf.


Any quick solution please?



Answer



This code should achieve what you have asked (not tested):


import arcpy
import os


mxd = arcpy.mapping.MapDocument(r"C:\temp\mymap.mxd")
output_folder = r"C:\temp"
ddp_lyr = mxd.dataDrivenPages.indexLayer
pdf_field = "RoadType"

#Get a list of unique values to group by
pdf_list = set([row[0] for row in arcpy.da.SearchCursor(ddp_lyr,pdf_field)])

for pdfName in pdf_list:
finalPdf = arcpy.mapping.PDFDocumentCreate(os.path.join(output_folder,pdfName + ".pdf"))

for i in range(1, mxd.dataDrivenPages.pageCount + 1):
mxd.dataDrivenPages.currentPageID = i
cur = str(mxd.dataDrivenPages.pageRow.getValue(pdf_field))
if cur == pdfName:
tempPdf = os.path.join(output_folder,"temp_" + cur + str(i) + ".pdf")
arcpy.mapping.ExportToPDF(mxd, tempPdf)
finalPdf.appendPages(tempPdf)
os.remove(tempPdf)
finalPdf.saveAndClose()
del finalPdf, tempPdf


The code is not optimised, so it loops over all the data driven pages for each unique value in the list. With some rearranging, it may be better to first export all the pdfs, then check the filenames for the unique value and group them accordingly.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...