+ Reply to Thread
Results 1 to 3 of 3

Thread: Print PDFs with Python?

  1. #1
    Caleb Mackey

    Join Date
    Jul 2012
    Posts
    297
    Points
    226
    Answers Provided
    27


    0

    Default Print PDFs with Python?

    People often come into my office requesting maps of their property. I have a script that will open up a command prompt window then allow the non-GIS users in my office to enter a Parcel ID number in the command window. Once user input has been accepted, the script will automatically select that parcel, zoom to it, then export it to PDF. I would like to add a print function to automatically print the PDF of the map. I know that I can use the PrintMap function to print straight from ArcMap, however, this does not come out very clear. I am wondering if anyone knows of a way to use python to print a PDF?
    Last edited by Caleb1987; 09-17-2012 at 01:58 PM.

  2. #2
    Luke Pinner
    Join Date
    May 2010
    Posts
    208
    Points
    124
    Answers Provided
    17


    1
    This post is marked as the answer

    Default Re: Print PDFs with Python?

    You can use the Adobe Reader command line print option. If you leave the printer name blank, reader will print to the default printer.
    Code:
    AcroRd32 /N /T PdfFile [PrinterName [ PrinterDriver [ PrinterPort ] ] ]
    Python example:
    Code:
    import subprocess
    
    printer='MyPrinter'
    pdffile=r'C:\Some Dir\some pdf.pdf'
    acroread=r'C:\Program Files (x86)\Adobe\Reader 9.0\Reader\AcroRd32.exe'
    
    #'"%s"'is to wrap double quotes around paths
    # as subprocess will use list2cmdline internally if we pass it a list
    #which escapes double quotes and Adobe Reader doesn't like that
    cmd='"%s" /N /T "%s" "%s"'%(acroread,pdffile,printer)
    
    proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    stdout,stderr=proc.communicate()
    exit_code=proc.wait()

  3. #3
    Caleb Mackey

    Join Date
    Jul 2012
    Posts
    297
    Points
    226
    Answers Provided
    27


    0

    Default Re: Print PDFs with Python?

    You are the smartest man alive!!! Thank you soo much, worked like a charm!

    Here is the code in case anyone is interested in doing something similar:

    Code:
    # This script allows a user to input a parcel ID number
    # This will automatically save the map to PDF so it can be printed
    # Written by Caleb Mackey  9/17/2012
    # Print PDF section courtesy of Luke Pinner 9/18/2012
    
    import arcpy, os, sys, traceback
    import subprocess
    arcpy.env.overwriteOutput = True
    
    def userinput():
        mxd = arcpy.mapping.MapDocument("G:\\Map_Documents\\Walkin_requests\\Customer_map.mxd")
        df = arcpy.mapping.ListDataFrames(mxd, "Main")[0]
        parcels = arcpy.mapping.ListLayers(mxd, "Parcels GIS Acres", df)[0]
        pdfpath = 'C:\\Documents and Settings\\gis\\Desktop\\PRINT_MAPS\\'
        txtfile = pdfpath + 'Parcelmap_ERROR.txt'
        acroread = r'C:\Program Files\Adobe\Reader 10.0\Reader\AcroRd32.exe'
        try:
            print "Enter Parcel Number WITHOUT dashes and hit ENTER"
            parcelid = raw_input()
            parcel_num = str(parcelid)
    
            print 'selecting parcel...'
            query = "SOL_PID ='%s'" % parcel_num
            arcpy.SelectLayerByAttribute_management(parcels, "NEW_SELECTION", query)
            result = arcpy.GetCount_management(parcels)
            if str(result) == '0':
                print 'Invalid SQL statement, check parcel ID'
                print 'Please verify the Parcel ID and try again'
                return userinput();
            
            elif str(result) > 0:
                df.zoomToSelectedFeatures()
                df.extent = parcels.getSelectedExtent(True)
                df.scale *= 1.65
                arcpy.RefreshActiveView()
    
                print 'Exporting to pdf...'
                pdf = pdfpath + str(parcel_num) + '.pdf'
                pdfname = str(parcel_num) + '.pdf'
                if arcpy.Exists(pdf):
                    arcpy.Delete_management(pdf)
                arcpy.mapping.ExportToPDF(mxd,pdfpath + str(parcel_num) + '.pdf')
    
                del mxd
                print 'PDF Exported, to view open ' + str(pdfname) + ' in the "PRINT MAPS" folder.'
                print 'Sending document to default printer'
    
                #### Print PDF Code thanks to Luke Pinner #####
                # '"%s"'is to wrap double quotes around paths
                # as subprocess will use list2cmdline internally if we pass it a list
                # which escapes double quotes and Adobe Reader doesn't like that
                cmd='"%s" /N /T "%s"' %(acroread,pdf)
    
                proc = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
                stdout,stderr=proc.communicate()
                exit_code=proc.wait()
                print 'Successful'
                        
        except:
               print arcpy.GetMessages(2)
    try:
        userinput()
            
    except:
        # Get the traceback object
        tb = sys.exc_info()[2]
        tbinfo = traceback.format_tb(tb)[0]
    
        # Concatenate information together concerning the error into a message string
        pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
        msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages(2) + "\n"
    
        # Return python error messages for use in script tool or Python Window
        arcpy.AddError(pymsg)
        arcpy.AddError(msgs)
    
        # Print Python error messages for use in Python / Python Window
        print pymsg + "\n"
        print msgs
    
        # Print Log file
        txtFile = open(txtfile, "w")
        txtFile.write(pymsg)
        txtFile.write(msgs)
        txtFile.write(query)
    
        txtFile.close()
    Last edited by Caleb1987; 09-18-2012 at 08:26 AM. Reason: Added code

+ Reply to Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts