#!/sw/bin/python2.4
import os,sys,tempfile
from AppKit import *
from Foundation import *

rr=64
gsBin = "gs"
board=NSPasteboard.generalPasteboard()
result = board.dataForType_(NSPDFPboardType)
if result:
	tmpdir = tempfile.mkdtemp("","clipPDF","/tmp")
	inname=tmpdir+"/infile.pdf"
	outname=tmpdir+"/outfile.pdf"
	result.writeToFile_atomically_(inname,1)
#
#       ghostscript (gs) is used to rewrite the PDF file. You may have to hard-code the path in gsBin:
#
	rr=os.spawnlp(os.P_WAIT,gsBin,gsBin,"-sDEVICE=pdfwrite", "-sOutputFile="+outname, "-q", "-dbatch", "-dNOPAUSE", inname, "-c", "quit")
	if rr==0:
		content=NSData.dataWithContentsOfFile_(outname)
		board.declareTypes_owner_([NSPDFPboardType], None)
		board.setData_forType_(content, NSPDFPboardType)
		os.remove(outname)
	os.remove(inname)
	os.rmdir(tmpdir)
sys.exit(rr)

