2008-05-06 13:50:19
昨日の青空文庫のxhtmlファイルをpdfに変換するスクリプトのMacOSX版である。必要ないのだが、別の用事でMacでもLaTeXを動かしたくなり、いろいろやっているうちにいつの間にか使えるようになったので、ついでに青空文庫変換スクリプトも使えるようにしてみた。しかし、どうしてLaTeXのコンパイル時のエラーがなくなったのかよく解らない。TeX Tools for miとかJIS X0212 for pTeXなど見ながらいろいろインストールしていたらいつの間にか動いていたのである。まあ、動いたからいいやといつものように投遣りな態度である。
さて、変換スクリプトは以下のようにした。
#!/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 = ereg_replace("\n ","\n",$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,"SJIS");
file_put_contents("./".$output.".tex",$txt);
exec("platex ".$output.".tex");
exec("dvipdfmx -p a5 ".$output.".dvi");
exec("open -a Preview ".$output.".pdf");
?>
昨日どうしてもうまくできなかった、行頭の(段落の最初の)空白が削除できた。出力は昨日はEUCだったのに対し、今日はShift-JIS。私の環境がそうだから。今日は/tmpフォルダは使っていないので、htmlファイルのあるところにいろいろなファイルが生成される。面倒臭いからそのままである。Macなので、最後にpdfファイルは「プレビュー」で開くようにした。exec("open -a Preview ".$output.".pdf"); というところ。昨日とほとんど変わらないけれど、下にできあがったpdfの第一ページを示す。
段落の頭が昨日は二文字分下がっていたのが、今日はちゃんと一文字分になっている。ただ、Macでこれを使って青空文庫を読む理由はあまりない。