« 2010年4月 | メイン | 2010年7月 »

2010年5月 4日

EPUB生成ライブラリを作ってみた

(2010/5/5 : githubにあげました)

EPUB生成のライブラリをrubyで作ってみました。ブツはこちら。http://github.com/skoji/gepub

  • コンテンツ指定のファイルは/content.opfに固定
  • identifierのschemeはURLに固定
  • identifierの名前はBookIDに固定

などなどいろいろ決め打ちにしています。

利用例はこんなです。

require 'rubygems'
require 'gepub'
require 'fileutils'


epubdir = "testepub" # epubのコンテンツを置くディレクトリ
title = "samplepub"  # epubのファイル名


FileUtils.rm_rf(epubdir)
FileUtils.mkdir(epubdir)

# epub メタデータ作成
epub = GEPUB::Generator.new(title)
epub.author="the author"
epub.publisher="the publisher"
epub.date = "2010-05-03"
epub.identifier = "http://www.skoji.jp/testepub/2010-05-03" # identifierはURLのみ

# サンプルのコンテンツ生成。通常は、別途作成しているはず。
[ 'coverpage', 'chapter1', 'chapter2' ].each {
  |name|
  File.open(epubdir + "/#{name}.html", 'w') {
    |file|
    file << <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml" lang="ja" xml:lang="ja">
  <head>
    <title>sample #{name} </title>
  </head>
  <body>
  <h1>#{name}</h1>
<p>here comes the contents for #{name}</p>
  </body>
</html>
EOF
  }
}

# "coverpage"は表紙を想定。従って目次のデータには入れない。
# spineに入れた順にリーダでは表示される。
epub.addManifest('cover', "coverpage.html", 'application/xhtml+xml')
epub.spine.push('cover')


epub.addManifest('chap1', "chapter1.html", 'application/xhtml+xml')
epub.spine.push('chap1')
epub.addNav('chap1', 'Chapter 1', "chapter1.html")

epub.addManifest('chap2', "chapter2.html", 'application/xhtml+xml')
epub.spine.push('chap2')
epub.addNav('chap1', 'Chapter 2', "chapter2.html")

# この他にcssとかイメージがあれば、それもManifestへ追加する。
# cssやイメージはspineやaddNavへの追加は不要。

# container.xml/contents.opf/toc.ncxなどのファイルを生成
epub.create(epubdir)

# 生成したディレクトリから、epubファイル作成
epub.create_epub(epubdir, ".")

サンプル書いて気付きましたが、EPUB::Creatorというクラスの役割がぶれてるなあ。