Skip to content

Instantly share code, notes, and snippets.

@evanlh
Created May 22, 2021 21:20
Show Gist options
  • Save evanlh/36a80557405653c60d75b51dbc9d3aae to your computer and use it in GitHub Desktop.
Save evanlh/36a80557405653c60d75b51dbc9d3aae to your computer and use it in GitHub Desktop.
#!/usr/bin/python
import sys
import os
from Quartz import PDFDocument
from Foundation import NSURL
if __name__ == '__main__':
if len(sys.argv) < 2:
raise TypeError('Must provide path')
path = sys.argv[1]
doit = len(sys.argv) > 2
files = [ x for x in os.listdir(path) if os.path.isfile(os.path.join(path, x)) ]
for file in files:
pdfURL = NSURL.fileURLWithPath_(os.path.join(path, file))
if not pdfURL:
continue
pdfDoc = PDFDocument.alloc().initWithURL_(pdfURL)
if not pdfDoc:
continue
metadata = pdfDoc.documentAttributes()
newfn = file
if 'Title' in metadata and 'Author' in metadata:
title = metadata['Title']
author = metadata['Author']
newfn = title + " - " + author + ".pdf"
elif 'Title' in metadata:
newfn = metadata['Title'] + '.pdf'
if newfn != file and len(newfn) > len(file):
print(newfn)
if doit:
try:
os.rename(os.path.join(path, file), os.path.join(path, newfn))
except:
print("Unexpected error:", sys.exc_info()[0])
print("Skipping " + file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment