def main(argv): inputfile = "" outputfile = "" filter = "" try: opts, args = getopt.getopt(argv,"hc:i:o:",["input=","creator=","output="]) except getopt.GetoptError: print 'creator.py -c <creator> -i <inputfile> -o <outputfile>' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'creator.py -c <filter> -i <inputfile> -o <outputfile>' print 'longnames are: --creator, --input, --output' print "If no output is specified, the input will be over-written." sys.exit() elif opt in ("-c", "--creator"): value = arg.decode('utf-8') elif opt in ("-i", "--input"): inputfile = arg.decode('utf-8') elif opt in ("-o", "--output"): outputfile = arg.decode('utf-8') print value, inputfile, outputfile if outputfile == "": outputfile = inputfile pdf_url = NSURL.fileURLWithPath_(inputfile) pdf_doc = CG.PDFDocument.alloc().initWithURL_(pdf_url) # Default value option: # if value == "": value = "Uncle Bob Silly" dict = { 'kCGPDFContextCreator': value } pdf_doc.writeToFile_withOptions_(outputfile, dict)
def main(argv): inputfile = "" outputfile = "" value="" try: opts, args = getopt.getopt(argv,"hc:i:o:",["creator=", "input=", "output="]) except getopt.GetoptError: print 'creator.py -c <creator> -i <inputfile> -o <outputfile>' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'creator.py -c <creator> -i <inputfile> -o <outputfile>' print 'longnames are: --creator, --input, --output' print "If no output is specified, the input will be over-written." sys.exit() elif opt in ("-c", "--creator"): value = arg.decode('utf-8') elif opt in ("-i", "--input"): inputfile = arg.decode('utf-8') elif opt in ("-o", "--output"): outputfile = arg.decode('utf-8') if outputfile == "": outputfile = inputfile pdfURL = NSURL.fileURLWithPath_(inputfile) pdfDoc = Quartz.PDFDocument.alloc().initWithURL_(pdfURL) # Default value option: # if value == "": value = "Uncle Bob Silly" options = { Quartz.kCGPDFContextCreator: value } pdfDoc.writeToFile_withOptions_(outputfile, options)
def setMetadata(argv): inputfile = "" outputfile = "" value="" try: opts, args = getopt.getopt(argv,"hc:i:o:",["creator=", "input=", "output="]) except getopt.GetoptError: print ('creator.py -c <creator> -i <inputfile> -o <outputfile>') sys.exit(2) for opt, arg in opts: if opt == '-h': print ('creator.py -c <creator> -i <inputfile> -o <outputfile>') print ('longnames are: --creator, --input, --output') print ("If no output is specified, the input will be over-written.") sys.exit() elif opt in ("-c", "--creator"): value = arg elif opt in ("-i", "--input"): inputfile = arg elif opt in ("-o", "--output"): outputfile = arg if outputfile == "": outputfile = inputfile pdfURL = NSURL.fileURLWithPath_(inputfile) pdfDoc = Quartz.PDFDocument.alloc().initWithURL_(pdfURL) # Default value option: # if value == "": value = "Uncle Bob Silly" options = { Quartz.kCGPDFContextCreator: value } pdfDoc.writeToFile_withOptions_(outputfile, options)
def main(incoming_args): backendName = os.path.basename(incoming_args[0]) destination = getDestination() logFile = os.path.join(destination, backendName) + ".log" if len(incoming_args) == 1: logger("direct %s \"Unknown\" \"Save to PDF\"\n" % backendName, None) sys.stdout.flush() sys.exit(0) if len(incoming_args) not in (6,7): sys.stdout.flush() logger("Wrong number of arguments. Usage: %s job-id user title copies options [file]\n" % backendName, None) sys.exit(1) global user jobID, user, title, copies, options = (incoming_args[1:6]) outFilename = os.path.join(destination, title) outFilename = os.path.splitext(outFilename)[0] logger(jobID+"\n", logFile) logger(user+"\n", logFile) logger(title+"\n", logFile) logger(copies+"\n", logFile) logger(options+"\n", logFile) # If 5 arguments, take PDF/PS file from stdin; if 6, take filename. if len(incoming_args) == 7: inFilename = incoming_args[6] fileRef = open(inFilename, 'r') fileType = fileRef.read(4) outFilename += getType(fileType) pdfURL = NSURL.fileURLWithPath_(inFilename) pdfDoc = PDFDocument.alloc().initWithURL_(pdfURL) encrypt(inFilename, pdfDoc) os.rename(inFilename, outFilename) else: fileType = sys.stdin.read(4) outFilename += getType(fileType) global myDataObject myDataObject = NSMutableData.alloc().initWithLength_(0) myDataObject.appendBytes_length_(fileType, len(fileType)) for myChunk in sys.stdin: myDataObject.appendBytes_length_(myChunk, len(myChunk)) pdfDoc = PDFDocument.alloc().initWithData_(myDataObject) encrypt(outFilename, pdfDoc) fileRef = open(outFilename, "w") fileRef.write(myDataObject.getBytes_length_(None, myDataObject.length())) fileRef.close # Fix file permissions of PDF for user fixPerms(outFilename) # Make sure everyone can read log. os.chmod(logFile, 0744)
def main(): for filename in sys.argv[1:]: shortName = os.path.splitext(filename)[0] outputfile = shortName+" text.txt" pdfURL = NSURL.fileURLWithPath_(filename) pdfDoc = PDFDocument.alloc().initWithURL_(pdfURL) if pdfDoc : pdfString = NSString.stringWithString_(pdfDoc.string()) pdfString.writeToFile_atomically_encoding_error_(outputfile, True, NSUTF8StringEncoding, None)
def main(): for filename in sys.argv[1:]: inputfile =filename.decode('utf-8') shortName = os.path.splitext(filename)[0] outputfile = shortName+" text.txt" pdfURL = NSURL.fileURLWithPath_(inputfile) pdfDoc = PDFDocument.alloc().initWithURL_(pdfURL) if pdfDoc : pdfString = NSString.stringWithString_(pdfDoc.string()) pdfString.writeToFile_atomically_encoding_error_(outputfile, True, NSUTF8StringEncoding, None)
def main(argv): inputfile = "" outputfile = "" filter = "" try: opts, args = getopt.getopt(sys.argv[1:], "ifo", ["input", "filter", "output"]) except getopt.GetoptError as err: print(err) usage() sys.exit(2) if len(args) != 3: print("Not enough arguments") sys.exit(2) inputfile = args[0].decode('utf-8') if not inputfile: print 'Unable to open input file' sys.exit(2) filter = args[1].decode('utf-8') filter = checkFilter(filter) if not filter: print 'Unable to find Quartz Filter' sys.exit(2) outputfile = args[2].decode('utf-8') if not outputfile: print 'No valid output file specified' sys.exit(2) # You could just take the inputfile as the outputfile if not explicitly given. # outputfile = inputfile pdfURL = NSURL.fileURLWithPath_(inputfile) pdfDoc = PDFDocument.alloc().initWithURL_(pdfURL) filterURL = NSURL.fileURLWithPath_(filter) value = QuartzFilter.quartzFilterWithURL_(filterURL) dict = {'QuartzFilter': value} pdfDoc.writeToFile_withOptions_(outputfile, dict)
def getDocInfo(file): pdfURL = NSURL.fileURLWithPath_(file) pdfDoc = Quartz.PDFDocument.alloc().initWithURL_(pdfURL) if pdfDoc: metadata = pdfDoc.documentAttributes() if "Keywords" in metadata: keys = metadata["Keywords"] mutableMetadata = metadata.mutableCopy() mutableMetadata["Keywords"] = tuple(keys) return mutableMetadata else: return metadata
def main(argv): inputfile = "" outputfile = "" filter = "" try: opts, args = getopt.getopt(sys.argv[1:], "ifo", ["input", "filter", "output"]) except getopt.GetoptError as err: print(err) usage() sys.exit(2) if len(args) != 3: print("Not enough arguments") sys.exit(2) inputfile =args[0].decode('utf-8') if not inputfile: print 'Unable to open input file' sys.exit(2) filter = args[1].decode('utf-8') filter = checkFilter(filter) if not filter: print 'Unable to find Quartz Filter' sys.exit(2) outputfile = args[2].decode('utf-8') if not outputfile: print 'No valid output file specified' sys.exit(2) # You could just take the inputfile as the outputfile if not explicitly given. # outputfile = inputfile pdfURL = NSURL.fileURLWithPath_(inputfile) pdfDoc = PDFDocument.alloc().initWithURL_(pdfURL) filterURL = NSURL.fileURLWithPath_(filter) value = QuartzFilter.quartzFilterWithURL_(filterURL) dict = { 'QuartzFilter': value } pdfDoc.writeToFile_withOptions_(outputfile, dict)
def main(argv): inputfile = "" outputfile = "" filter = "" try: opts,args = getopt.getopt (sys.argv[1:], '', []) except getopt.GetoptError: usage () sys.exit (1) if len (args) != 3: usage () sys.exit (1) filter = args[0] if not filter: print 'Unable to create context filter' sys.exit (1) inputfile = args[1] if not inputfile: print 'Unable to open input file' sys.exit (1) else: inputfile = inputfile.decode('utf-8') outputfile = args[2] if not outputfile: print 'Unable to create output context' sys.exit (1) else: outputfile = outputfile.decode('utf-8') pdf_url = NSURL.fileURLWithPath_(inputfile) pdf_doc = CG.PDFDocument.alloc().initWithURL_(pdf_url) furl = NSURL.fileURLWithPath_(filter) value = QuartzFilter.quartzFilterWithURL_(furl) dict = { 'QuartzFilter': value } pdf_doc.writeToFile_withOptions_(outputfile, dict)
def doRotate(filename): shortName = os.path.splitext(filename)[0] outFilename = shortName + "+90.pdf" pdfURL = NSURL.fileURLWithPath_(filename) pdfDoc = PDFDocument.alloc().initWithURL_(pdfURL) if pdfDoc: pages = pdfDoc.pageCount() for p in range(0, pages): page = pdfDoc.pageAtIndex_(p) existingRotation = page.rotation() newRotation = existingRotation + 90 page.setRotation_(newRotation) pdfDoc.writeToFile_(outFilename)
def main(argv): inputfile = "" outputfile = "" filter = "" try: opts, args = getopt.getopt(sys.argv[1:], "fio", ["filter", "input", "output"]) except getopt.GetoptError as err: print(err) usage() sys.exit(2) if len(args) != 3: print("Not enough arguments") sys.exit(2) filter = args[0].decode('utf-8') if not filter: print 'Unable to create context filter' sys.exit(2) inputfile = args[1].decode('utf-8') if not inputfile: print 'Unable to open input file' sys.exit(2) outputfile = args[2].decode('utf-8') if not outputfile: print 'Unable to create output context' sys.exit(2) pdfURL = NSURL.fileURLWithPath_(inputfile) pdfDoc = PDFDocument.alloc().initWithURL_(pdfURL) filterURL = NSURL.fileURLWithPath_(filter) value = QuartzFilter.quartzFilterWithURL_(filterURL) dict = {'QuartzFilter': value} pdfDoc.writeToFile_withOptions_(outputfile, dict)
def trimPDF(filename): # filename = filename.decode('utf-8') shortName = os.path.splitext(filename)[0] outFilename = shortName + " TPS.pdf" pdfURL = NSURL.fileURLWithPath_(filename) pdfDoc = PDFDocument.alloc().initWithURL_(pdfURL) if pdfDoc: pages = pdfDoc.pageCount() for p in range(0, pages): page = pdfDoc.pageAtIndex_(p) mediaBoxSize = page.boundsForBox_(mediabox) trimBoxSize = CGRectMake(margins[0], margins[1], (mediaBoxSize.size.width - margins[2] - margins[0]), (mediaBoxSize.size.height - margins[3] - margins[1])) page.setBounds_forBox_(trimBoxSize, mediabox) pdfDoc.writeToFile_(outFilename)
def trimPDF(filename): filename = filename.decode('utf-8') shortName = os.path.splitext(filename)[0] outFilename = shortName + " TPS.pdf" pdfURL = NSURL.fileURLWithPath_(filename) pdfDoc = PDFDocument.alloc().initWithURL_(pdfURL) if pdfDoc: pages = pdfDoc.pageCount() for p in range(0, pages): page = pdfDoc.pageAtIndex_(p) mediaBoxSize = page.boundsForBox_(mediabox) trimBoxSize = CGRectMake(margins[0], margins[1], (mediaBoxSize.size.width - margins[2] - margins[0]), (mediaBoxSize.size.height - margins[3] - margins[1])) page.setBounds_forBox_(trimBoxSize, mediabox) pdfDoc.writeToFile_(outFilename)
def encrypt(filename): if not filename: print ('Unable to open input file') sys.exit(2) shortName = os.path.splitext(filename)[0] outputfile = shortName+" locked.pdf" pdfURL = NSURL.fileURLWithPath_(filename) pdfDoc = PDFDocument.alloc().initWithURL_(pdfURL) if pdfDoc : options = { kCGPDFContextAllowsCopying: False, kCGPDFContextAllowsPrinting: False, kCGPDFContextOwnerPassword: copyPassword, kCGPDFContextUserPassword: openPassword} pdfDoc.writeToFile_withOptions_(outputfile, options) return
def process(self): # Veriify if the path provided exists if not os.path.exists(self.path): raise ActionError('the path provided could not be found') # Create the new item's bookmark and properties url = NSURL.fileURLWithPath_(self.path) properties = {'com.apple.loginitem.HideOnLaunch': self.hidden} # Find a specific login item login_items = LSSharedFileListCreate( None, kLSSharedFileListSessionLoginItems, None) if self.state == 'present': # Search for the login item in the existing login items for login_item in login_items.allItems(): login_item_url, error = LSSharedFileListItemCopyResolvedURL( login_item, 0, None) # The item path was found and has the same hidden setting if (not error and login_item_url.path() == url.path() and login_item.properties() ['com.apple.loginitem.HideOnLaunch'] == self.hidden): return self.ok() # Add (or update) the login item to the list LSSharedFileListInsertItemURL(login_items, kLSSharedFileListItemLast, None, None, url, properties, None) return self.changed() else: # 'absent' # Search for the login item in the existing login items found_item = None for login_item in login_items.allItems(): login_item_url, error = LSSharedFileListItemCopyResolvedURL( login_item, 0, None) # The item path was found so we delete it if not error and login_item_url.path() == url.path(): found_item = login_item break if not found_item: return self.ok() LSSharedFileListItemRemove(login_items, found_item) return self.changed()
def trimPDF(filename): hasBeenChanged = False filename = filename.decode('utf-8') shortName = os.path.splitext(filename)[0] outFilename = shortName + " TPS.pdf" pdfURL = NSURL.fileURLWithPath_(filename) pdfDoc = PDFDocument.alloc().initWithURL_(pdfURL) if pdfDoc: pages = pdfDoc.pageCount() for p in range(0, pages): page = pdfDoc.pageAtIndex_(p) mediaBoxSize = page.boundsForBox_(mediabox) trimBoxSize = page.boundsForBox_(trimbox) if not CGRectEqualToRect(mediaBoxSize, trimBoxSize): page.setBounds_forBox_(trimBoxSize, mediabox) hasBeenChanged = True if hasBeenChanged: pdfDoc.writeToFile_(outFilename)
def main(): inputfile = "" outputfile = "" for filename in sys.argv[1:]: inputfile =filename.decode('utf-8') if not inputfile: print 'Unable to open input file' sys.exit(2) shortName = os.path.splitext(filename)[0] outputfile = shortName+" locked.pdf" pdfURL = NSURL.fileURLWithPath_(inputfile) pdfDoc = PDFDocument.alloc().initWithURL_(pdfURL) if pdfDoc : options = { kCGPDFContextAllowsCopying: False, kCGPDFContextAllowsPrinting: False, kCGPDFContextOwnerPassword: password, kCGPDFContextUserPassword: ""} pdfDoc.writeToFile_withOptions_(outputfile, options)
def debooklet(filename): shortName = os.path.splitext(filename)[0] outFilename = shortName + " paged.pdf" # If running python2, uncomment the following line: # filename = filename.decode('utf-8') pdfURL = NSURL.fileURLWithPath_(filename) leftPDF = PDFDocument.alloc().initWithURL_(pdfURL) rightPDF = PDFDocument.alloc().initWithURL_(pdfURL) newPDF = PDFDocument.alloc().init() if leftPDF: if not (doPageOne): leftPage = leftPDF.pageAtIndex_(0) newPDF.insertPage_atIndex_(leftPage, 0) pages = leftPDF.pageCount() startPage = int(not (doPageOne)) for p in range(startPage, pages): outPageCount = newPDF.pageCount() leftPage = leftPDF.pageAtIndex_(p) rightPage = rightPDF.pageAtIndex_(p) mediaBoxSize = leftPage.boundsForBox_(mediabox) rotation = leftPage.rotation() if (rotation == 0) or (rotation == 180): halfway = (mediaBoxSize.size.width / 2) pageHeight = mediaBoxSize.size.height leftHandCrop = CGRectMake(0, 0, halfway, pageHeight) rightHandCrop = CGRectMake(halfway, 0, halfway, pageHeight) leftPage.setBounds_forBox_(leftHandCrop, mediabox) rightPage.setBounds_forBox_(rightHandCrop, mediabox) else: halfway = (mediaBoxSize.size.height / 2) pageWidth = mediaBoxSize.size.width topCrop = CGRectMake(0, 0, pageWidth, halfway) bottomCrop = CGRectMake(0, halfway, pageWidth, halfway) leftPage.setBounds_forBox_(topCrop, mediabox) rightPage.setBounds_forBox_(bottomCrop, mediabox) newPDF.insertPage_atIndex_(leftPage, outPageCount) newPDF.insertPage_atIndex_(rightPage, outPageCount + 1) newPDF.writeToFile_(outFilename)
def setMetadata(filename): options = {} author = 'Ben Byram-Wigfield' creator = 'PDFSuite Python Scripts' subject = '' keywords = 'PDF Magic' # Get Title from filename. Or delete these two lines and set a string value. title = os.path.basename(filename) title = os.path.splitext(title)[0] authorKey = Quartz.kCGPDFContextAuthor creatorKey = Quartz.kCGPDFContextCreator subjectKey = Quartz.kCGPDFContextSubject keywordsKey = Quartz.kCGPDFContextKeywords titleKey = Quartz.kCGPDFContextTitle filename = filename.decode('utf-8') shortName = os.path.splitext(filename)[0] pdfURL = NSURL.fileURLWithPath_(filename) pdfDoc = Quartz.PDFDocument.alloc().initWithURL_(pdfURL) # Default value option: if author: options[authorKey] = author if creator: options[creatorKey] = creator if subject: options[subjectKey] = subject if keywords: options[keywordsKey] = keywords if title: options[titleKey] = title print options # To save to a separate file, uncomment the next line. # filename = shortName + " data.pdf" pdfDoc.writeToFile_withOptions_(filename, options)
def setMetadata(filename): options = {} author='Ben Byram-Wigfield' creator = 'PDFSuite Python Scripts' subject = '' keywords = 'PDF Magic' # Get Title from filename. Or delete these two lines and set a string value. title = os.path.basename(filename) title = os.path.splitext(title)[0] authorKey = Quartz.kCGPDFContextAuthor creatorKey = Quartz.kCGPDFContextCreator subjectKey = Quartz.kCGPDFContextSubject keywordsKey = Quartz.kCGPDFContextKeywords titleKey = Quartz.kCGPDFContextTitle filename = filename.decode('utf-8') shortName = os.path.splitext(filename)[0] pdfURL = NSURL.fileURLWithPath_(filename) pdfDoc = Quartz.PDFDocument.alloc().initWithURL_(pdfURL) # Default value option: if author: options[authorKey] = author if creator: options[creatorKey] = creator if subject: options[subjectKey] = subject if keywords: options[keywordsKey] = keywords if title: options[titleKey] = title print options # To save to a separate file, uncomment the next line. # filename = shortName + " data.pdf" pdfDoc.writeToFile_withOptions_(filename, options)
def createOutputContextWithPath(path, dictarray): url = NSURL.fileURLWithPath_(path) return Quartz.CGPDFContextCreateWithURL(url, None, dictarray)
def createPDFDocumentFromPath(path): url = NSURL.fileURLWithPath_(path) return Quartz.CGPDFDocumentCreateWithURL(url)
def createPDFDocumentWithPath(path): # return Quartz.CGPDFDocumentCreateWithURL(Quartz.CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, path, len(path), False)) url = NSURL.fileURLWithPath_(path) return Quartz.CGPDFDocumentCreateWithURL(url)
def mock_resolve_url(in_item, in_flags, out_error): # pylint: disable=unused-argument url = NSURL.fileURLWithPath_(in_item.path()) error = None return url, error
#!/usr/bin/python # RINSE PDF v1.0 : This script will re-save a PDF, which may fix some errors in the PDF data. # by Ben Byram-Wigfield import sys import os import Quartz as Quartz from CoreFoundation import NSURL for inputfile in sys.argv[1:]: outfile = inputfile # To save with a new name, uncomment the lines below. # prefix = os.path.splitext(inputfile) # outfile = prefix[0] + 'rinsed.pdf' pdfURL = NSURL.fileURLWithPath_(inputfile) pdfDoc = Quartz.PDFDocument.alloc().initWithURL_(pdfURL) pdfDoc.writeToFile_(outfile)
def createPDFDocumentWithPath(path): path = path.decode('utf-8') pdfURL = NSURL.fileURLWithPath_(path) if pdfURL: return Quartz.PDFDocument.alloc().initWithURL_(pdfURL)
#!/usr/bin/env python3 # Make PDFX: Create a PDF/X-3 compliant document # v.3.0 Now written in python 3 # import sys import os import Quartz as Quartz from CoreFoundation import (NSURL, QuartzFilter) filterpath = os.path.expanduser("~/Library/Filters/Better PDFX-3.qfilter") if not os.path.exists(filterpath): filterpath = "/System/Library/Filters/Create Generic PDFX-3 Document.qfilter" print("Using System filter, which is not very good") for inputfile in sys.argv[1:]: prefix = os.path.splitext(inputfile) outfile = prefix[0] + 'X.pdf' pdfURL = NSURL.fileURLWithPath_(inputfile) pdfDoc = Quartz.PDFDocument.alloc().initWithURL_(pdfURL) if pdfDoc: filterURL = NSURL.fileURLWithPath_(filterpath) value = QuartzFilter.quartzFilterWithURL_(filterURL) options = {'QuartzFilter': value} pdfDoc.writeToFile_withOptions_(outfile, options)
# by Ben Byram-Wigfield v2.1 # There are two ways to rotate a PDF page/file. # 1: Create a new PDF context, graphically transform each page of the original and save the file. # 2: Adjust the 'rotation' parameter in each page. # This is the 2nd way, which is easier. # It also preserves DocInfo and other metadata. import sys import os from Quartz import PDFDocument from CoreFoundation import NSURL if __name__ == '__main__': for filename in sys.argv[1:]: filename = filename.decode('utf-8') shortName = os.path.splitext(filename)[0] outFilename = shortName + "+90.pdf" pdfURL = NSURL.fileURLWithPath_(filename) pdfDoc = PDFDocument.alloc().initWithURL_(pdfURL) pages = pdfDoc.pageCount() for p in range(0, pages): page = pdfDoc.pageAtIndex_(p) existingRotation = page.rotation() newRotation = existingRotation + 90 page.setRotation_(newRotation) pdfDoc.writeToFile_(outFilename)
def createPDFDocumentFromPath(path): pdfURL = NSURL.fileURLWithPath_(path) if pdfURL: return Quartz.PDFDocument.alloc().initWithURL_(pdfURL)
def getDocInfo(file): file = file.decode('utf-8') pdfURL = NSURL.fileURLWithPath_(file) pdfDoc = Quartz.PDFDocument.alloc().initWithURL_(pdfURL) return pdfDoc.documentAttributes()
def setMetadata(filename): pdfURL = NSURL.fileURLWithPath_(filename) pdfDoc = Quartz.PDFDocument.alloc().initWithURL_(pdfURL) value = os.path.splitext(filename)[0] options = {Quartz.kCGPDFContextTitle: value} pdfDoc.writeToFile_withOptions_(outputfile, options)