2008-05-05 17:53:46
青空文庫で「トカトントン」など読んでゐると、ふと不安になった。MacOSXで読んでゐる今は、T-Timeで読んでいるのだが、Linuxで読みたいときはどうすればいいのかと考えると不安で仕方がなくなってきた。何かLinux用の縦書きビューアもあるらしいのだが、どうもいろいろ設定やら名にやら面倒臭いようだ。ということで、今日はPHPとLaTeXで即席青空文庫ビューアを作ってみた。
#!/usr/bin/php
<?php
$fname = $argv[1];
$output = $argv[2];
if (empty($output)){
$output = "output";
}
$fcont = file_get_contents($fname);
$fenc = mb_detect_encoding($fcont);
$fcont = mb_convert_encoding($fcont,"UTF-8",$fenc);
$fcont = ereg_replace("\x0D\x0A|\x0A|\x0D","\n",$fcont);
$fcont = ereg_replace("\n","\n\n",$fcont);
$fcont = ereg_replace("\t","",$fcont);
$fcont = ereg_replace("<br >","<br />",$fcont);
$fcont = ereg_replace("<br /><br />","<br />\n<br />",$fcont);
$fcont = preg_replace("/^ /","",$fcont);
$fcont = ereg_replace("<ruby><rb>","\\ruby{",$fcont);
$fcont = ereg_replace("</rp><rt>","}{",$fcont);
$fcont = ereg_replace("</rt><rp>","}",$fcont);
$fcont = ereg_replace("(}","}",$fcont);
$fcont = ereg_replace("})","}",$fcont);
$fcont = preg_replace("/<title>.+?<\/title>/","",$fcont);
$ttl0 = strpos($fcont,"<h1 class=\"title\">");
$ttl1 = strpos($fcont,"</h1>",$ttl0);
$title = strip_tags(substr($fcont,$ttl0,$ttl1-$ttl0));
$au0 = strpos($fcont,"<h2 class=\"author\">");
$au1 = strpos($fcont,"</h2>",$au0);
$author = strip_tags(substr($fcont,$au0,$au1-$au0));
$fcont = preg_replace("/<title>.+?<\/title>/","",$fcont);
$fcont = preg_replace("/<h1 class=\"title\">.+?<\/h1>/","",$fcont);
$fcont = preg_replace("/<h2 class=\"author\">.+?<\/h2>/","",$fcont);
$fcont = strip_tags($fcont);
$txt = "\documentclass[a5j]{tarticle}\n";
$txt .= "\usepackage{okumacro}\n";
$txt .= "\begin{document}\n";
$txt .= "{\huge ".$title."}\n\n";
$txt .= "\begin{flushright}\n";
$txt .= "{\large ".$author." }\n";
$txt .= "\end{flushright}\n\n";
$txt .= $fcont;
$txt .= "\end{document}\n";
$txt = mb_convert_encoding($txt,"EUC-JP");
file_put_contents("/tmp/".$output.".tex",$txt);
exec("platex -output-directory='/tmp/' ".$output.".tex");
if ($output == "output"){
exec("dvipdfmx -o /tmp/".$output.".pdf -p a5 /tmp/".$output.".dvi");
exec("acroread /tmp/".$output.".pdf &");
}else{
exec("dvipdfmx -p a5 /tmp/".$output.".dvi");
exec("acroread ".$output.".pdf &");
}
?>
ubuntu 7.04や7.10ではこれで動いた。PHPの内部文字コードがUTF8用なので、そうでない人は変えないと文字化けするかも知れない。ちなみに私のMacOSXでは動かなかった。出力ファイル(.tex)はEUC。これを例えば"tagegaki.php"という名前で保存して、php tategaki.php ファイル名 という感じで入力してやると/tmpディレクトリ内に、ルビのタグをLaTeX用に変換したり、htmlタグを除去したりしたtexファイルを保存し、そこでplatexを実行してから、できたdviファイルをdvipdfmxでpdfファイルに変換するという仕組みになっている。青空文庫のxhtmlファイル名に続いて出力ファイル名(拡張子なし)を入れれば最後のpdfファイルはカレント・ディレクトリに出力される。platexで"-output-directory='xx'"とするとdviファイルやlogファイルなどが出力される場所を指定できると初めて知った。dvipdfmxでは出力ディレクトリを"-o"で指定するとか、ここで"-p a5"のやうに用紙を指定することを初めて知った。できあがるのは、下のような画面。

数ページから数十ページまでならこれでいいのだが、 500ページを越えるような場合には、途中で止まってしまう。texファイルの出力が完了する前にdvipdfmxが動き出してしまうのか。よく解らないけど。texが出力されたあとに、手入力でコマンドを入れてやればファイルはちゃんとできる。段落の最初が二文字下がってしまう。行頭の空白の削除がうまく実行されない。面倒臭いから、もういいや。