Created
March 11, 2016 01:19
-
-
Save j6s/ba4a48262449acc6beba to your computer and use it in GitHub Desktop.
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 ruby | |
require 'colorize' | |
HEADER = %Q{ | |
pdfcompress: compresses a pdf using graphicsmagick. | |
Author: Johannes Hertenstein | |
Usage: | |
$pdfcompress.rb $input $output [$quality] | |
- $input: path of the original file. Can be absolute or relative. | |
- $output: path of the new file that will be created. Can be absolute or relative | |
- $quality: (optional) The quality level that should be used to compress. will default to "ebook" | |
Available levels (from lowest to highest): | |
- screen | |
- ebook | |
- printer | |
- prepress | |
} | |
validQualities = ["screen", "ebook", "printer", "prepress"]; | |
# executes a command, prints stdout to commandline and returns it to the caller | |
def execute(cmd, out = true) | |
puts "$ #{cmd}".blue; | |
lines = []; | |
IO.popen(cmd) {|io| | |
io.each { |line| | |
print line.light_black if out; | |
lines.push(line); | |
} | |
} | |
Process.waitall(); | |
return lines.join("\n"); | |
end | |
# | |
# If there are not enough parameters, we show the header | |
# | |
if ARGV.length < 2 | |
puts HEADER; | |
exit(1); | |
end | |
# | |
# getting the arguments | |
# | |
infile = ARGV[0]; | |
outfile = ARGV[1]; | |
quality = validQualities[1]; | |
if ARGV.length > 2 | |
quality = ARGV[2]; | |
end | |
# | |
# checking the arguments | |
# | |
if !File.exists?(infile) | |
puts HEADER.light_black; | |
puts "Error: input file #{infile} does not exist".red; | |
exit(2); | |
end | |
if File.exists?(outfile) | |
puts HEADER.light_black; | |
puts "Error: output file #{outfile} already exists".red; | |
exit(3); | |
end | |
if !validQualities.include?(quality) | |
puts HEADER.light_black; | |
puts "Error: quality #{quality} is not valid. Must be one of #{validQualities}".red; | |
exit(4); | |
end | |
puts "Using quality level #{quality}"; | |
# | |
# Do the magick | |
# | |
execute("gs -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=\"/#{quality}\" -sOutputFile=\"#{outfile}\" \"#{infile}\""); | |
# | |
# outputs the size of the input and output files in MB | |
# TODO: dynamically choose other units | |
# | |
sizeIn = (File.size(infile) / 1024 / 1024).round(2); | |
sizeOut = (File.size(outfile) / 1024 / 1024).round(2); | |
puts "\n"; | |
puts "Input file: #{sizeIn} MB".green; | |
puts "Output file: #{sizeOut} MB".green; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment