rd2latex + Rake で画像を PDF に入れてみよう
使用するものはこいつら。
あとは外部コマンドを色々。Debian なら aptitude ですぐにインストールできる。 把握してるのはこんだけ。
- convert
- 画像を png -> eps に変換する
- platex
- TeX -> dvi に変換する
- dvipdfmx
- dvi -> pdf に変換する
Rakefile
require 'rake/clean'
require 'strscan'
$KCODE='e'
CLEAN.include('*.tex','*.dvi','*.aux','*.log')
CLOBBER.include('*.pdf','*.sxi')
SRC = FileList['**/*.rd']
DVI = SRC.ext('.dvi')
PDF = DVI.ext('.pdf')
target = 'print.pdf'
desc "make print.pdf"
file "print.pdf" => ["print.dvi"]
rule '.tex' => '.rd' do |t|
metadata = meta(t.source)
sh <<EOD
rd2 --require=rd/rd2latex-lib \
--documentclass="jarticle" \
--documentclass-option="a4j" \
--preamble-file="#{File.dirname(__FILE__)}/preamble.tex" \
--title="#{metadata['title']}" \
--author="#{metadata['author']}" \
--date="#{metadata['date']}" \
--maketitle \
--no-section-number \
#{t.source} > #{t.name}
EOD
end
PNG = FileList['*.png']
EPS = PNG.ext('.eps')
EPS.zip(PNG) do |eps, png|
file eps => png
end
desc "create print.rd"
file 'print.rd' => ['print.rd.in'] + SAMPLE + EPS do |t|
str = implant(t.prerequisites.first)
File.open(t.name, 'w+') do |f|
f.write(str)
end
end
rule '.eps' => '.png' do |t|
sh "convert #{t.source} -format eps #{t.name}"
end
rule '.dvi' => '.tex' do |t|
2.times{ sh "platex #{t.source}" }
end
rule '.pdf' => '.dvi' do |t|
sh "dvipdfmx #{t.source}"
end
def meta(filename)
ret = {}
File.readlines(filename).each do |line|
%w[title author date].each do |item|
if m = /^#{item}: "(.+)"/.match(line)
ret[item] = m[1]
next
end
end
end
ret
end
def implant(target)
scanner = StringScanner.new(File.read(target))
ret = ''
re = /^(?:(\s*)#include "(.*?)")|(?:\s*#image "(.*?)", "(.*?)")/
until scanner.eos?
ret <<
case scanner.scan(re)
when /#include/
arr = File.read(scanner[2]).to_a
Array.new(arr.size){|i| i + 1 }.zip(arr).map{|line|
"#{scanner[1]}#{'%02d' % line[0]}: #{line[1].chomp}"
}.join('').gsub(/\n+/,"\n")
when /#image/
filename = scanner[3].split('.').first
option = scanner[4]
implant_image_helper(filename, option)
"\n<<< #{filename}"
else
scanner.getch
end
end
ret
end
def implant_image_helper(filename, options)
File.open("#{filename}.tex", 'w') do |f|
f.puts '\begin{center}'
f.puts " \\includegraphics[#{options}]{#{filename}.eps}"
f.puts '\end{center}'
end
end
こんな Rakefile をさっくり準備する。
で RD なファイルを準備。ついでに sample.rb と sample.png も用意しとく。
print.rd.in
title: "かいしんのいちげきの出し方"
author: "武闘家"
date: "2007年09月23日"
=begin
= include とか
#include "sample.rb"
= 画像とか
#ここに画像
#image "sample.eps", "width=15cm,clip"
=endsample.rb
10.times do
puts "hello"
end上記のファイルを変換すると以下のようになる。
print.rd
title: "かいしんのいちげきの出し方"
author: "武闘家"
date: "2007年09月23日"
=begin
= include とか
01: 10.times do
02: puts "hello"
03: end
= 画像とか
#ここに画像
<<< sample
=endこんなんになって最終的には tex -> div -> pdf になるのです。
説明したりない部分があるけど、とりあえず今日はここまで。