Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add directory walk #6

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 11 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Pdfc -- PDF Compressor
Simple python script to compress PDF.

Installation
-------------
----
* Install dependency Ghostscript.
On MacOSX: `brew install ghostscript`
On Windows: install binaries via [official website] (https://www.ghostscript.com/)
Expand All @@ -14,23 +14,25 @@ On Windows: install binaries via [official website] (https://www.ghostscript.com
On MacOSX:
`echo export=/absolute/path/of/the/folder/script/:$PATH >> ~/.bash_profile`

Or with ZSH
`echo path+=absolute/path/of/the/folder/script/ >> ~/.zshrc`

Usage
-----
----
`pdfc [-o output_file_path] [-c number] input_file_path`

Ex:
`pdfc -o out.pdf in.pdf`

Output:
```
Compress PDF...
Compression by 65%.
Final file size is 1.4MB
Done.
```
Compress PDF...
Compression by 65%.
Final file size is 1.4MB
Done.

When compression did not work, the file is skipped.
Options
-------
----
* `-c` or `--compress` specifies 5 levels of compression, similar to standard pdf generator level:
* 0: default
* 1: prepress
Expand Down
77 changes: 56 additions & 21 deletions pdf_compressor.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
from shutil import copyfile


def compress(input_file_path, output_file_path, power=0):
def compress(input_file_path, output_file_path, backup, power=0):
"""Function to compress PDF via Ghostscript command line interface"""
quality = {
0: '/default',
Expand All @@ -46,19 +46,51 @@ def compress(input_file_path, output_file_path, power=0):
sys.exit(1)

print("Compress PDF...")
initial_size = os.path.getsize(input_file_path)
subprocess.call(['gs', '-sDEVICE=pdfwrite', '-dCompatibilityLevel=1.4',
'-dPDFSETTINGS={}'.format(quality[power]),
'-dNOPAUSE', '-dQUIET', '-dBATCH',
'-sOutputFile={}'.format(output_file_path),
input_file_path]
)

initial_size = os.path.getsize(input_file_path)
final_size = os.path.getsize(output_file_path)
ratio = 1 - (final_size / initial_size)
print("Compression by {0:.0%}.".format(ratio))
print("Final file size is {0:.1f}MB".format(final_size / 1000000))
print("Done.")

# Check if compressing was resourceful
if (final_size > initial_size) or (final_size == initial_size):
os.remove(output_file_path)
print("Skipped")
# In case no output file is specified, erase original file
elif output_file_path == 'temp.pdf':
if backup:
copyfile(input_file_path, input_file_path.replace(".pdf", "_BACKUP.pdf"))
os.remove(input_file_path)
copyfile(output_file_path, input_file_path)
os.remove(output_file_path)

ratio = 1 - (final_size / initial_size)
print("Compression by {0:.0%}.".format(ratio))
print("Final file size is {0:.1f}MB".format(final_size / 1000000))
print("Done.")

def compress_directory(input_dir_path, backup, power=0):

# Default File Path
output_file_path = os.path.join(input_dir_path, "temp.pdf")

# The extension to search for
exten = '.pdf'

for dirpath, dirnames, files in os.walk(input_dir_path):

for name in files:
if name.lower().endswith(exten):
file_path = os.path.join(dirpath, name)
compress(file_path, output_file_path, backup, power)

for dirname in dirnames:
new_dir_path = os.path.join(dirpath, dirname)
compress_directory(new_dir_path, backup, power)

def main():
parser = argparse.ArgumentParser(
Expand All @@ -80,22 +112,25 @@ def main():
if not args.out:
args.out = 'temp.pdf'

# Run
compress(args.input, args.out, power=args.compress)

# In case no output file is specified, erase original file
if args.out == 'temp.pdf':
if args.backup:
copyfile(args.input, args.input.replace(".pdf", "_BACKUP.pdf"))
copyfile(args.out, args.input)
os.remove(args.out)

# In case we want to open the file after compression
if args.open:
if args.out == 'temp.pdf' and args.backup:
subprocess.call(['open', args.input])
else:
subprocess.call(['open', args.out])
if os.path.isdir(args.input):
compress_directory(args.input, args.backup, power=args.compress)
elif os.path.isfile(args.input):
# Run
compress(args.input, args.out, args.backup, power=args.compress)

# In case we want to open the file after compression
if args.open:
if args.out == 'temp.pdf' and args.backup:
subprocess.call(['open', args.input])
else:
subprocess.call(['open', args.out])

else:
print("Error: invalid path for input PDF file")
sys.exit(1)



if __name__ == '__main__':
main()