Close ArcMap using Python AddIn Extension

3650
15
Jump to solution
09-09-2013 03:58 AM
EricMahaffey
New Contributor III
I've written a couple of Python scripts that open ArcMap, run a Python AddIn Extension, then hopefully close ArcMap.  As an MXD document is opened, the AddIn extension runs the [HTML]def beforeCloseDocument(self):[/HTML] function.  However I can't seem to figure out how to close ArcMap after the MXD has completely opened.  Basically I'm trying to work around a known bug in which the ExportToPDF and PrintMap functions will not work correctly with layouts that have attribute tables embeded in them.  Here's the code from my AddIn Extension.  Any advice would be much apprciated.  I'm hitting a wall here, and just can't seem to get anywhere with this.

[HTML]import arcpy
import pythonaddins
import os
import time


class ExtensionClass1(object):
    """Implementation for PrintToPDF_AddIn_addin.extension2 (Extension)"""
    def __init__(self):
        # For performance considerations, please remove all unused methods in this class.
        self.enabled = True

    def openDocument(self):
        mxd = arcpy.mapping.MapDocument("CURRENT")
        if mxd.description == 'Print to PDF':
            #time.sleep(30)
            #os.system("pause")
            os.system('taskkill /IM Arcmap*')#is killing it too soon
            #time.sleep(15)
        pass
           
    def beforeCloseDocument(self):
        #mxd = arcpy.mapping.MapDocument("CURRENT")
        if mxd.description == 'Print to PDF':
            arcpy.mapping.PrintMap(mxd, r"Adobe PDF", "PAGE_LAYOUT")
        pass[/HTML]
Tags (2)
0 Kudos
15 Replies
StacyRendall1
Occasional Contributor III
Hi Eric,

I was trying to spend a bit of time looking into this, but I cannot get Add-In Extensions working on my computer (Buttons and Menus work OK, but Extensions are never added to the Extensions dialog box for me to activate them)...

Anyway, I have a suspicion that the only method being run is the openDocument method, as forcing Arc to close is not necessarily the same thing as closing the MXD...

What I was going to test on my computer is the following:
import arcpy
import pythonaddins

class testExtension(object):
    """Implementation for arcAddin_addin.testExtension (Extension)"""
    def __init__(self):
        # For performance considerations, please remove all unused methods in this class.
        self.enabled = True
        self.testTxt = open('D:\\_TEMP\\testOutput.txt', 'w')
        self.testTxt.write('File created')
        self.testTxt.flush()
    def openDocument(self):
        self.testTxt.write('!! openDocument method...')
        self.testTxt.flush()
        mxd = arcpy.mapping.MapDocument("CURRENT")
        if mxd.description == 'Print to PDF':
            self.testTxt.write('\t\tDocument contains "Print to PDF" description')
            self.testTxt.flush()
            arcpy.mapping.PrintMap(mxd, r"Adobe PDF", "PAGE_LAYOUT")
            layers = arcpy.mapping.ListLayers(mxd, "", "Layers"):
            self.testTxt.write('\t\t%s' % str(layers))
            self.testTxt.flush()
            self.testTxt.write('\t\tAbout to kill ArcMap')
            self.testTxt.flush()
            os.system('taskkill /IM Arcmap*')
            self.testTxt.write('\t\tThis probably will not appear in the file...')
            self.testTxt.flush()
        else:
            self.testTxt.write('\t\tDocument DOES NOT contain "Print to PDF" description')
            self.testTxt.flush()
    def beforeCloseDocument(self):
        self.testTxt.write('!! beforeCloseDocument method')
        self.testTxt.flush()
    def closeDocument(self):
        self.testTxt.write('!! closeDocument method')
        self.testTxt.flush()


It writes to a text file as each method occurs, so you can see what the add-in extension is doing. flush() is used to force the writes to the file, as we won't be closing it properly. Are you able to temporarily replace your add-in extension python file with the above (after changing the path of the text file to something more appropriate), run it as you normally would and post the contents of the text file?
0 Kudos
EricMahaffey
New Contributor III
Stacy,

I've had some success.  I'm running late getting out of the office today, but I plan to write it all up on Monday.  Your never going to believe how I got it to work.  Sorry to leave you hanging in suspense over the weekend.

Eric
0 Kudos
MattSayler
Occasional Contributor II
As an aside, do you have an Esri account manager assigned to your company? Might be worth pounding on them some if support hasn't been helpful. This seems like a big enough deal for your company that it is absolutely reasonable to escalate it, especially if you're paying yearly maintenance.
0 Kudos
StacyRendall1
Occasional Contributor III
Stacy,

I've had some success.  I'm running late getting out of the office today, but I plan to write it all up on Monday.  Your never going to believe how I got it to work.  Sorry to leave you hanging in suspense over the weekend.

Eric


Great, look forward to hearing what works!

Cheers,
Stacy
0 Kudos
EricMahaffey
New Contributor III
OK, here's what I finally figured out.  It all comes down to the "Zoom To Percentage" in the map layout.  All along I???ve noticed that printing to a PDF file seemed to build the layout tables correctly, but the table would be too small.

In ArcMap:
[ATTACH=CONFIG]27486[/ATTACH]

The resulting Output PDF:
[ATTACH=CONFIG]27487[/ATTACH]

However when I changed the "Zoom to Percentage" in the layout, the results looked like this:

In ArcMap:
[ATTACH=CONFIG]27488[/ATTACH]

The resulting Output PDF:
[ATTACH=CONFIG]27489[/ATTACH]

Go figure as to why, but it works!  For me my magic number was 245%.  I think it'll vary for each user depending on how they have their toolbars setup, etc.  This value also applied to both 8.5x11 and 11x17 landscape layouts.

So as a recap I used this script to launch ArcMap and open the MXD file:
import arcpy import subprocess  strArcMapPath = r"C:\Program Files (x86)\ArcGIS\Desktop10.1\bin\ArcMap.exe" strMxd = r"D:\Users\Products\PSA Map Updates\Automation\PSA Location Map - Final.mxd"  objNewProcess = subprocess.Popen([strArcMapPath, strMxd]) objNewProcess.wait() # this line will wait for the new process to end  print "Script completed successfully."


Then this one as my Python AddIn script:
import arcpy import pythonaddins  class ExtensionClass1(object):     """Implementation for PrintToPDF_AddIn_addin.extension2 (Extension)"""     def __init__(self):         # For performance considerations, please remove all unused methods in this class.         self.enabled = True      def openDocument(self):         mxd = arcpy.mapping.MapDocument("CURRENT")         if mxd.description == 'Print to PDF':             arcpy.mapping.PrintMap(mxd, r"Adobe PDF", "PAGE_LAYOUT")


Now I was orignally trying to close ArcMap in order to execute the PrintMap function before close, however this method works at open.  I still can't believe it.  Keep in mind that this process requires a PDF print driver of some sort in order to work.  I have Adobe Acrobat installed which includes an "Adobe PDF" driver, however there are a few freebies out there that shouldwork just as well (i.e. CutePDF, etc...)

I plan to forward this to out customer support rep to see if that will help move things along with the bug fix.  Thanks for all the input, and assistance.  If anyone has any questions feel free to contact me.
0 Kudos
StacyRendall1
Occasional Contributor III
Great! Glad you were able to work it out!
0 Kudos