Guest User

Untitled

a guest
Mar 23rd, 2018
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. #!/usr/bin/env ruby
  2. # -*- ruby -*-
  3.  
  4. require 'combine_pdf'
  5. require 'pdf-reader'
  6. require 'optparse'
  7. require 'ostruct'
  8.  
  9. class PDFSplitArgumentParser
  10. def self.parse(args)
  11. options = OpenStruct.new
  12. options.first_page = 1
  13.  
  14. opts = OptionParser.new { |opts|
  15. opts.banner = "Usage: pdfsplit [options] <input> <output>"
  16. opts.separator ""
  17. opts.separator "Specific options:"
  18.  
  19. opts.on("-f", "--first-page PAGE", Integer, "Specify the first page to begin spliting at") { |f| options.first_page = f }
  20. opts.on("-l", "--last-page PAGE", Integer, "Specify the last page to split") { |l| options.last_page = l }
  21.  
  22. options[:help] = opts.help
  23. }
  24.  
  25. opts.parse!(args)
  26. options
  27. end
  28. end
  29.  
  30. options = PDFSplitArgumentParser.parse(ARGV)
  31. if ARGV.length != 2 then
  32. abort options[:help]
  33. end
  34.  
  35. input_arg = ARGV[0]
  36. output_arg = ARGV[1]
  37.  
  38. if !input_arg.end_with?(".pdf") || !File.file?(input_arg) then
  39. abort "Please specify a valid input file: #{input_arg}"
  40. end
  41.  
  42. last_page = options.last_page || PDF::Reader.new(input_arg).page_count
  43.  
  44. input_pdf = CombinePDF.load(input_arg)
  45. output_pdf = CombinePDF.new
  46.  
  47. pages = 0
  48. input_pdf.pages.each { |page|
  49. if (pages += 1) >= options.first_page && pages <= last_page then
  50. output_pdf << page
  51. end
  52. }
  53.  
  54. output_pdf.save "#{output_arg}#{output_arg.end_with?("pdf") ? "" : ".pdf"}"
Add Comment
Please, Sign In to add comment