Skip to content

Instantly share code, notes, and snippets.

@hayamiz
Created August 20, 2012 14:00
Show Gist options
  • Save hayamiz/3404339 to your computer and use it in GitHub Desktop.
Save hayamiz/3404339 to your computer and use it in GitHub Desktop.
A4の紙に4ページを短編綴じで印刷してホチキス止めすると,袋綴じ状になるよう面付けするスクリプト。ホチキス止めした後に小口をカッターで切るとA5冊子として完成する。
#!/usr/bin/env ruby
require 'optparse'
def parse_args(argv)
opt = Hash.new
parser = OptionParser.new
parser.banner = "#{$0} [options] INPUT_PDF_FILE"
opt[:output] = nil
parser.on('-o', '--output FILE') do |file|
opt[:output] = file
end
parser.parse!(argv)
opt[:input] = argv.first
if ! opt[:input].is_a? String
$stderr.puts("ERROR: Please specify input file")
puts(parser.help)
exit(false)
end
if ! File.exists?(opt[:input])
raise ArgumentError.new("No such file: #{opt[:input]}")
end
if ! opt[:input] =~ /\.pdf\Z/
raise ArgumentError.new("Input is not a pdf file: #{opt[:input]}")
end
if opt[:output].nil?
opt[:output] = opt[:input].gsub(/\.pdf\Z/, ".A5seihon.pdf")
end
opt
end
def main(argv)
opt = parse_args(argv)
pages = `pdfinfo "#{opt[:input]}"|grep Pages|awk '{print $2}'`.to_i
pdftk_page_ranges = []
p [pages, (pages.to_f / 4).ceil, pages / 4 + 1]
(pages.to_f / 4).ceil.times do |nth_paper|
base_page = nth_paper * 4 + 1
remaining_pages = pages - (base_page - 1)
case remaining_pages
when 0
raise RuntimeError.new()
when 1
pdftk_page_ranges << base_page
when 2
pdftk_page_ranges << base_page
pdftk_page_ranges << base_page + 1 # dummy
pdftk_page_ranges << base_page + 1 # dummy
pdftk_page_ranges << base_page + 1
when 3
pdftk_page_ranges << base_page
pdftk_page_ranges << base_page + 2 # dummy
pdftk_page_ranges << base_page + 2
pdftk_page_ranges << base_page + 1
else
pdftk_page_ranges << base_page
pdftk_page_ranges << base_page + 3
pdftk_page_ranges << base_page + 2
pdftk_page_ranges << base_page + 1
end
end
cmd = ["pdftk", opt[:input], "cat", pdftk_page_ranges , "output", opt[:output]].flatten.map(&:to_s)
puts(cmd.join(' '))
system(*cmd)
end
if __FILE__ == $0
main(ARGV.dup)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment