DataDrivenPages (arcpy.mapping)

Summary

Provides access to methods and properties for managing the individual pages within a map document that has Data Driven Pages enabled.

Discussion

Map series can be created without any scripting at all by using the Data Driven Pages toolbar from within ArcMap. The reverse is also true: map series can be completely scripted using arcpy.mapping without using the Data Driven Pages user interface in ArcMap, but there are good reasons for combining both techniques. The ArcMap Data Driven Pages toolbar may not provide enough options for creating the "perfect" map series, but the inherent behavior of a Data Driven Pages-enabled map document can save many lines of code because the page extents, scales, dynamic text, and so forth, are all managed automatically within the map document so that code does not need to be written.

An example of this would be a scenario where a text element's string information needs to be formatted using custom logic or needs to be constructed from multiple fields. It would be unnecessary to have to do everything in arcpy.mapping just because of such a simple, custom requirement. In this case, the map document can still be authored with Data Driven Pages enabled, and arcpy.mapping can handle the custom text element string requirements. A code sample below addresses this scenario.

Data Driven Pages must first be enabled and authored within a map document (.mxd) using the Data Driven Pages toolbar in ArcMap before it can be referenced with arcpy.mapping.

The DataDrivenPages class only has a single exportToPDF method but that does not mean other export files can't be created. See the first code sample below.

For more information about Data Driven Pages, see the following topics:

Properties

PropertyExplanationData Type
currentPageID
(Read and Write)

The currentPageID property represents the active or current page for a map document (.mxd) that has Data Driven Pages enabled. This value is displayed in the Data Driven Pages toolbar when Show Page is selected; it represents the x of x of y.

Long
dataFrame
(Read Only)

Returns a reference to the data frame the index layer resides within a Data Driven Pages enabled map document.

DataFrame
indexLayer
(Read Only)

Returns a reference to the index layer in a Data Driven Pages enabled map document.

Layer
pageCount
(Read Only)

The pageCount property returns the total page count for a map document (.mxd) that has Data Driven Pages enabled. This value is displayed in the Data Driven Pages toolbar when Show Page is selected; it represents the y of x of y.

Long
pageNameField
(Read Only)

Returns a field object that represents the field used in the index feature class when setting up Data Driven Pages.

Field
pageRow
(Read Only)

Use pageRow to return the index layer's row object for the active or current page. The index layer fields can then be read and/or modified as necessary.

Row
selectedPages
(Read Only)

Returns a Python list of index numbers that represent selected index layer features in a Data Driven Pages enabled map document.

List

Method Overview

MethodExplanation
exportToPDF (out_pdf, {page_range_type}, {page_range_string}, {multiple_files}, {resolution}, {image_quality}, {colorspace}, {compress_vectors}, {image_compression}, {picture_symbol}, {convert_markers}, {embed_fonts}, {layers_attributes}, {georef_info}, {jpeg_compression_quality}, {show_selection_symbology})

Exports a specified set of pages to a multipage PDF document for a map document (.mxd) that has Data Driven Pages enabled

getPageIDFromName (page_name)

Returns a Data Driven Pages index value based on the name of the page

printPages ({printer_name}, {page_range_type}, {page_range_string}, {out_print_file}, {show_selection_symbology})

Prints specific pages from a Data Driven Pages-enabled map document (.mxd) to a specified printer

refresh ()

Refreshes an existing Data Driven Pages series

Methods

exportToPDF (out_pdf, {page_range_type}, {page_range_string}, {multiple_files}, {resolution}, {image_quality}, {colorspace}, {compress_vectors}, {image_compression}, {picture_symbol}, {convert_markers}, {embed_fonts}, {layers_attributes}, {georef_info}, {jpeg_compression_quality}, {show_selection_symbology})
ParameterExplanationData Type
out_pdf

A string that represents the path and file name for the output export file.

String
page_range_type

The string value that designates how the pages will be printed, similar to the Pages tab within the ArcMap Export Map dialog box for PDF documents.

  • ALLAll pages are exported.
  • CURRENTThe active page is exported.
  • RANGEOnly pages listed in the page_range_string parameter will be exported.
  • SELECTEDSelected index layer features/pages are exported.

(The default value is ALL)

String
page_range_string

A string that identifies the pages to be printed if the RANGE option in the page_range_type parameter is used (for example, 1, 3, 5-12).

String
multiple_files

An option to control how the output PDF is created. By default, all pages are exported into a single, multipage document. You can also specify that individual, single-page PDF documents be exported using two different options.

  • PDF_MULTIPLE_FILES_PAGE_NAMEExport single-page documents using the page name for the output file name.
  • PDF_MULTIPLE_FILES_PAGE_INDEXExport single-page documents using the page index value for the output file name.
  • PDF_SINGLE_FILEExport a multipage document.

(The default value is PDF_SINGLE_FILE)

String
resolution

An integer that defines the resolution of the export file in dots per inch (dpi).

(The default value is 300)

Integer
image_quality

A string that defines output image quality.

  • BESTAn output image quality resample ratio of 1
  • BETTERAn output image quality resample ratio of 2
  • NORMALAn output image quality resample ratio of 3
  • FASTERAn output image quality resample ratio of 4
  • FASTESTAn output image quality resample ratio of 5

(The default value is BEST)

String
colorspace

A string that defines the color space of the export file.

  • CMYKCyan, magenta, yellow, and black color model
  • RGBRed, green, and blue color model

(The default value is RGB)

String
compress_vectors

A Boolean that controls compression of vector and text portions of the output file. Image compression is defined separately.

(The default value is True)

Boolean
image_compression

A string that defines the compression scheme used to compress image or raster data in the output file.

  • ADAPTIVEAutomatically selects the best compression type for each image on the page. JPEG will be used for large images with many unique colors. DEFLATE will be used for all other images.
  • JPEGA lossy data compression.
  • DEFLATEA lossless data compression
  • LZWLempel-Ziv-Welch, a lossless data compression
  • NONECompression not applied
  • RLERun-length encoded compression

(The default value is ADAPTIVE)

String
picture_symbol

A string that defines whether picture markers and picture fills will be converted to vector or rasterized on output.

  • RASTERIZE_BITMAP Rasterize layers with bitmap markers/fills.
  • RASTERIZE_PICTURERasterize layers with any picture markers/fills.
  • VECTORIZE_BITMAPVectorize layers with bitmap markers/fills.

(The default value is RASTERIZE_BITMAP)

String
convert_markers

A Boolean that controls the conversion of character-based marker symbols to polygons. This allows the symbols to appear correctly if the symbol font is not available or cannot be embedded. However, setting this parameter to True disables font embedding for all character-based marker symbols, which can result in a change in their appearance.

(The default value is False)

Boolean
embed_fonts

A Boolean that controls the embedding of fonts in an export file. Font embedding allows text and character markers to be displayed correctly when the document is viewed on a computer that does not have the necessary fonts installed.

(The default value is True)

Boolean
layers_attributes

A string that controls inclusion of PDF layer and PDF object data (attributes) in the export file.

  • LAYERS_ONLYExport PDF layers only.
  • LAYERS_AND_ATTRIBUTESExport PDF layers and feature attributes.
  • NONENo setting is applied.

(The default value is LAYERS_ONLY)

String
georef_info

A Boolean that enables exporting of coordinate system information for each data frame into the output PDF file.

(The default value is True)

Boolean
jpeg_compression_quality

A number that controls compression quality value when image_compression is set to ADAPTIVE or JPEG. The valid range is 1 to 100. A jpeg_compression_quality of 100 provides the best quality images but creates large export files. The recommended range is between 70 and 90.

(The default value is 80)

Integer
show_selection_symbology

A Boolean that controls whether the selection symbology should be displayed in the output.

(The default value is False)

Boolean

Data Driven Pages are exported to a multipage PDF document. The map document must have Data Driven Pages enabled. PDF files are designed to be consistently viewable and printable across different platforms. They are commonly used for distributing documents on the Web and are becoming a standard interchange format for content delivery. ArcMap PDFs are editable in many graphics applications and retain annotation, labeling, and attribute data for map layers from the ArcMap table of contents. PDF exports from ArcMap support embedding of fonts and thus can display symbology correctly even if the user does not have Esri fonts installed. PDF exports from ArcMap can define colors in CMYK or RGB values.

Refer to the Exporting your map topic in ArcGIS for Desktop Help for more detailed discussions on exporting maps.

getPageIDFromName (page_name)
ParameterExplanationData Type
page_name

A value in the index layer that corresponds to the Name field that was used to set up Data Driven Pages

String

Many of the Data Driven Pages properties and methods use an internal index value rather than the literal names of the pages used to create the index layer. The index values are automatically generated based on the Name and Sort fields. It may not be obvious which index value represents a specific page. The getPageIDFromName method provides a mechanism for this translation.

pageID = mxd.dataDrivenPages.getPageIDFromName("HarborView")
mxd.dataDrivenPages.currentPageID = pageID
printPages ({printer_name}, {page_range_type}, {page_range_string}, {out_print_file}, {show_selection_symbology})
ParameterExplanationData Type
printer_name

A string that represents the name of a printer on the local computer.

(The default value is None)

String
page_range_type

The string value that designates how the pages will be printed, similar to the Pages tab within the ArcMap Export Map dialog box for PDF documents.

  • ALLAll pages are exported.
  • CURRENTThe active page is exported.
  • RANGEOnly pages listed in the page_range_string parameter will be exported.
  • SELECTEDSelected index layer features/pages are exported.

(The default value is ALL)

String
page_range_string

A string that identifies the pages to be printed if the RANGE option in the page_range_type parameter is used (for example, 1, 3, 5-12).

String
out_print_file

A path that includes the name of an output print file. The format created is dependent on the printer. If you're using a PostScript printer, the format will be PostScript, and it is recommended that a .ps extension be provided. If you're using a Windows printer, use a .prn extension.

(The default value is None)

String
show_selection_symbology

A Boolean that controls whether the selection symbology should be displayed in the output.

(The default value is False)

Boolean

The ListPrinterNames() function is an easy way to get the string for the printer_name parameter.

NoteNote:

Driver based printing is not supported on ArcGIS for Server. For Data Driven Pages printing tasks as geoprocessing services, use the exportToPDF function in the DataDrivenPages class. For information on general printing in web applications see Printing in web applications.

The following script prints a specific set of Data Driven Pages to a local printer:

import arcpy
mxd = arcpy.mapping.MapDocument(r"C:\Project\ParcelAtlas.mxd")
mxd.dataDrivenPages.printPages(r"\\olyfile\OLYCanon", "RANGE", "1,3,5-12")
refresh ()

You will want to use the refresh method if one of the following occurs: (1) features are added to or deleted from your index layer; (2) edits are made to the Sort or Name field values; (3) the data frame extent is changed due to zooming, panning, or change to map scale; or (4) edits are made to any field being used by Data Driven Pages for an index layer feature that is driving the current geographic extent. Data Driven Pages will retain the original settings in these cases until the refresh method is executed.

Code Sample

DataDrivenPages example 1

The following script exports each page of a Data Driven Pages series into an individual PNG file.

import arcpy
mxd = arcpy.mapping.MapDocument(r"C:\Project\ParcelAtlas.mxd")
for pageNum in range(1, mxd.dataDrivenPages.pageCount + 1):
    mxd.dataDrivenPages.currentPageID = pageNum
    print "Exporting page {0} of {1}".format(str(mxd.dataDrivenPages.currentPageID), str(mxd.dataDrivenPages.pageCount))
    arcpy.mapping.ExportToPNG(mxd, r"C:\Project\OutPut\ParcelAtlas_Page" + str(pageNum) + ".png")
del mxd
DataDrivenPages example 2

The following script will print only a set of map pages using a list of page names and also modifies text element map title information using customized logic that can only be accomplished within the scripting environment (in other words, the title string is custom built based on an attribute value). The script loops through each named page and sets the currentPageID accordingly. It then extracts the value from a field in the index layer called TRS. It next parses the values, strips away leading zeros, reconstructs the text element title string, and sends the results to a printer.

import arcpy
mxd = arcpy.mapping.MapDocument(r"C:\Project\ParcelAtlas.mxd")
pageNameList = ["MPB", "PJB", "AFB", "ABB"]
for pageName in pageNameList:
    pageID = mxd.dataDrivenPages.getPageIDFromName(pageName)
    mxd.dataDrivenPages.currentPageID = pageID
    fieldValue = mxd.dataDrivenPages.pageRow.TSR  #example values from a field called TSR are "080102", "031400"
    TRSTitle = arcpy.mapping.ListLayoutElements(MXD, "TEXT_ELEMENT", "TRSTitle")[0]
    township, range, section = fieldValue[:2].strip("0"), fieldValue[2:-2].strip("0"), fieldValue[-2:].strip("0")
    if section != "": 
        TRSTitle.text = "Section {0} T.{1}N. R.{2}W. W.M.".format(section, township, range)
    else:
        TRSTitle.text = "T.{0}N. R.{1}W. W.M.".format(township, range)
    mxd.dataDrivenPages.printPages(r"\\olyfile\SUITE_303", "CURRENT")
del mxd
DataDrivenPages example 3

The following script will export only the selected index pages (pages 1-10) out to individual PDF files. The resulting PDFs will have the index number appended to the output file name.

import arcpy
mxd = arcpy.mapping.MapDocument(r"C:\Project\ParcelAtlas.mxd")
ddp = mxd.dataDrivenPages
indexLayer = ddp.indexLayer
arcpy.SelectLayerByAttribute_management(indexLayer, "NEW_SELECTION",  
                                        '"PageNumber" >= 1 AND "PageNumber" <= 10')
for indexPage in ddp.selectedPages:
  ddp.currentPageID = indexPage
  ddp.exportToPDF(r"C:\Project\Output\Page" + str(indexPage) + ".pdf", "CURRENT")

del mxd
3/3/2014