Last active
April 6, 2016 16:53
-
-
Save j-faria/6bd0c975143a4575b35e033f60c1e29d to your computer and use it in GitHub Desktop.
Convert a PDF file to black&white and display it
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" | |
Convert a PDF file to black&white and display it. | |
Run as: python bw.py input.pdf | |
""" | |
viewer = 'evince' | |
from contextlib import contextmanager | |
import tempfile | |
import shutil | |
import os | |
import subprocess | |
import argparse | |
## emulate Python 3.2's tempfile.TemporaryDirectory() | |
@contextmanager | |
def TemporaryDirectory(): | |
name = tempfile.mkdtemp() | |
try: | |
yield name | |
finally: | |
shutil.rmtree(name) | |
def _parser(): | |
parser = argparse.ArgumentParser(description=__doc__) | |
parser.add_argument('input', help='The input PDF file') | |
parser.add_argument('-s', default=False, action='store_true', | |
help='Save the output PDF as input-bw.pdf') | |
return parser.parse_args() | |
if __name__ == '__main__': | |
args = _parser() | |
assert args.input.endswith('.pdf'), 'Input file must have .pdf extension' | |
with TemporaryDirectory() as tmpdirname: | |
# print('created temporary directory', tmpdirname) | |
output = os.path.join(tmpdirname, 'output.pdf') | |
cmd = ['gs', | |
'-q', | |
'-sOutputFile=%s' % output, | |
'-sDEVICE=pdfwrite', | |
'-sColorConversionStrategy=Gray', | |
'-dProcessColorModel=/DeviceGray', | |
'-dCompatibilityLevel=1.4', | |
'-dNOPAUSE', | |
'-dBATCH', | |
args.input, | |
] | |
subprocess.call(cmd) | |
subprocess.call([viewer, output]) | |
if args.s: | |
# saving output | |
savefile = '-bw'.join(os.path.splitext(args.input)) | |
print('Saving B&W PDF to %s' % savefile) | |
shutil.copy2(output, savefile) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment