Last active
August 29, 2015 14:13
-
-
Save maraigue/d577624f9d141591ac6d to your computer and use it in GitHub Desktop.
「1ページに、指定されたPDFの複数ページを印刷する」形式のPDFを作る
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 'tmpdir' | |
require 'fileutils' | |
# このスクリプトができること | |
# | |
# 「1ページに、指定されたPDFの複数ページを印刷する」形式のPDFを作る。 | |
# 隙間なく敷き詰められる。 | |
# 「横に何列並べるか」と「元のPDFのページの縮小率」が指定できる。 | |
# (縮小率については、実際には比率ではなく、変換後の横幅で指定する) | |
# | |
# 事前準備 | |
# | |
# シェルで以下のコマンドが使えることを確認 | |
# ・psselect | |
# ・latex | |
# ・dvipdfmx | |
# | |
# APTが使える環境の場合 | |
# $ sudo apt-get install texlive psutils | |
# texliveは時間がかかるので注意 | |
# | |
# 1ページあたり何列印刷するか | |
COLUMNS = 2 | |
# | |
# PDFを実際に出力する際の1枚あたりの横幅(縦幅は自動計算) | |
IMAGEWIDTH = '7cm' | |
# なお、最終的に出力されたPDFを印刷する際は「ページの拡大/縮小」オプションを | |
# 「なし」にすること。「用紙に合わせる」や「大きいページを縮小」では | |
# サイズが合わなくなる。 | |
# 出力ファイルの名前(実際には拡張子が補われる) | |
TEXFILE_BASE = 'result' | |
# ページごとに分割されたPostScriptファイルを格納しておくディレクトリ | |
OUTDIR = 'ps' | |
# 上記PostScriptファイルに付けるファイル名の数字の桁数 | |
DIGITS = 6 | |
def run_command(cmd) | |
STDERR.puts cmd | |
buf = `#{cmd}` | |
if $? != 0 | |
raise "Error in running command: #{cmd}" | |
end | |
buf | |
end | |
def main(fname) | |
if fname =~ /\.pdf\z/i | |
title = $` | |
unless File.file?(title) | |
STDERR.puts "Error: File #{title} not found" | |
return | |
end | |
else | |
title = fname | |
unless (File.file?("#{title}.pdf") || File.file?("#{title}.PDF")) | |
STDERR.puts "Error: File #{title} not found" | |
return | |
end | |
end | |
FileUtils.remove_entry_secure(OUTDIR, true) | |
FileUtils.mkdir_p(OUTDIR) | |
run_command "pdf2ps '#{title}.pdf'" | |
n = 1 | |
while true | |
outfile = sprintf("%s/%0#{DIGITS}d.ps",OUTDIR, n) | |
buf = run_command("psselect #{n} '#{title}.ps' '#{outfile}' 2>&1") | |
buf =~ /(\d+) page/ | |
if $1 == "0" | |
FileUtils.rm outfile | |
break | |
end | |
n += 1 | |
end | |
open(TEXFILE_BASE, "w") do |f| | |
f.puts <<TEX | |
\\documentclass{article} | |
\\usepackage[top=1cm,bottom=1cm,left=1cm,right=1cm]{geometry} | |
\\usepackage[dvips]{graphicx} | |
\\begin{document} | |
\\parindent = 0pt | |
TEX | |
Dir.glob("#{OUTDIR}/*.ps").sort.each_with_index do |img, i| | |
f.puts "\\includegraphics[width=#{IMAGEWIDTH}]{#{img}}" | |
if i % COLUMNS == COLUMNS - 1 | |
f.puts "\\\\" | |
end | |
end | |
f.puts "\\end{document}" | |
end | |
run_command("latex #{TEXFILE_BASE}") | |
run_command("dvipdfmx #{TEXFILE_BASE}") | |
puts "============================================================" | |
puts "Completed!" | |
puts "Resulted PDF is \"#{TEXFILE_BASE}.pdf\"." | |
puts "============================================================" | |
end | |
main(ARGV[0]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment