Sphinxを使ってPDFドキュメントを生成する

続きを書きました(2010/2/16)

ユーザ向けのドキュメントを作成するのによいツールがないかと探していたのですが、SphinxというPythonのドキュメント作成に使われているツールを試してみました。SphinxではreStructuredTextというマークアップ言語で記述したファイルからHTML、HTML Help、PDFなどを自動生成することができます。

今までWordファイルからPDFとHTMLを作成していたのですが、自動生成されるHTMLはそのままでは使えず手作業で修正しており、これをいい加減なんとかしたいと思っていました。

以下は、Windows環境にて一からPDF形式のドキュメントを生成できるようになるまでの手順のメモです。

Pythonのインストール

Pythonをインストールします。Python2.6のWindows用インストーラでインストールしてPATHを設定しました。
http://www.python.org/

setuptools 0.6c11のインストール

easy_installを使うために、setuptoolsをインストールします。
http://pypi.python.org/pypi/setuptools

Sphinxのインストール

easy_installを使用してSphinxをインストールします。
http://pypi.python.org/pypi/Sphinx

easy_install eggファイルのURL

プロジェクトの作成

sphinx-quickstartコマンドを実行してsphinxのプロジェクトの雛形を作成します。プロジェクト名や作者などを聞かれるので適当に入力します。

sphinx-quickstart

日本語の設定

config.pyを開いて以下の行を変更します。

language = 'ja'

これでテンプレートから自動生成される部分が日本語化されます。

HTMLの作成

まずはHTML形式を作成してみます。コマンドプロンプトにて、ドキュメントのフォルダに移動して、以下のコマンドを実行します。

>make html

これで、_build\htmlフォルダにHTML形式のドキュメントが作成されます。

PDFの作成

まず、PDFの作成に必要なプログラムをインストールして設定を行います。

rst2pdf

reStructuredTextをPDFに変換するためのrst2pdfをインストールします。

easy_install rst2pdf
Report Lab Toolkit

rst2pdfから利用するためのPython用PDF生成ライブラリであるReport Lab Toolkitをインストールします。
http://www.reportlab.org/oss/rl-toolkit/

Python Imaging Library(PIL)

画像ファイルの処理ためにPython Imaging Libraryをインストールします。
http://www.pythonware.com/products/pil/

埋め込み用フォントのインストール

PDFファイルに埋め込むためにIPAフォントVLゴシックフォントをインストールします。
otf,ttfファイルをC:\Windows\Fontsフォルダにコピーします。

本当はフォントを埋め込まないPDFを作成したかったのですが、うまくいかなかったので埋め込む形式で作成しています。

スタイルシートの作成

以下の内容でスタイルシートを作成します。ファイル名はja.jsonとしました。

{
  "embeddedFonts" :
[["VL-Gothic-Regular.ttf","VL-PGothic-Regular.ttf","ipam.otf","verdanaz.ttf"]],
  "fontsAlias" : {
    "stdFont": "VL-PGothic-Regular",
    "stdBold": "VL-PGothic-Regular",
    "stdItalic": "VL-PGothic-Regular",
    "stdBoldItalic": "VL-PGothic-Regular",
    "stdMono": "VL-Gothic-Regular"
  },
  "styles" : [
    ["base" , {
      "wordWrap": "CJK"
    }],
    ["literal" , {
      "wordWrap": "None"
    }]
  ]
}
rst2pdfからのPDF作成

まずは、rst2pdfからPDFファイルを作成してみます。

rst2pdf -s ja --font-path=C:\WINDOWS\Fonts -o index.pdf index.rst

これで日本語を含むPDFが正常に作成できました。

Sphinxからrst2pdfを実行する設定

Sphinxからrst2pdfを実行するための設定を、config.pyに設定を追加します。これはrst2pdfのマニュアルに書かれているとおりです。

まず、extensionsの部分に以下を追加します。

extensions = ['sphinx.ext.autodoc','rst2pdf.pdfbuilder']

次にPDF用の設定を追加し、pdf_documents、pdf_font_path、pdf_stylesheetsあたりを編集します。

# -- Options for PDF output --------------------------------------------------

# Grouping the document tree into PDF files. List of tuples
# (source start file, target name, title, author, options).
#
# If there is more than one author, separate them with \\.
# For example: r'Guido van Rossum\\Fred L. Drake, Jr., editor'
#
# The options element is a dictionary that lets you override 
# this config per-document.
# For example, 
# ('index', u'MyProject', u'My Project', u'Author Name', 
#  dict(pdf_compressed = True))
# would mean that specific document would be compressed
# regardless of the global pdf_compressed setting.

pdf_documents = [ 
('index', u'MyProject', u'My Project', u'Author Name'),
]

# A comma-separated list of custom stylesheets. Example:
pdf_stylesheets = ['sphinx','kerning','a4','ja']

# Create a compressed PDF
# Use True/False or 1/0
# Example: compressed=True
#pdf_compressed = False

# A colon-separated list of folders to search for fonts. Example:
pdf_font_path = ['c:\windows\fonts']

# Language to be used for hyphenation support
pdf_language = "ja"

# Mode for literal blocks wider than the frame. Can be
# overflow, shrink or truncate
#pdf_fit_mode = "shrink"

# Section level that forces a break page.
# For example: 1 means top-level sections start in a new page
# 0 means disabled
#pdf_break_level = 0

# When a section starts in a new page, force it to be 'even', 'odd',
# or just use 'any'
#pdf_breakside = 'any'

# Insert footnotes where they are defined instead of 
# at the end.
#pdf_inline_footnotes = True

# verbosity level. 0 1 or 2
#pdf_verbosity = 0

# If false, no index is generated.
#pdf_use_index = True

# If false, no modindex is generated.
#pdf_use_modindex = True

# If false, no coverpage is generated.
#pdf_use_coverpage = True

# Documents to append as an appendix to all manuals.    
#pdf_appendices = []

# Enable experimental feature to split table cells. Use it
# if you get "DelayedTable too big" errors
#pdf_splittables = False
   
# Set the default DPI for images
#pdf_default_dpi = 72

make.batに以下の記述を追加します。

if "%1" == "pdf" (
	%SPHINXBUILD% -b pdf %ALLSPHINXOPTS% %BUILDDIR%/pdf
	echo.
	echo.Build finished. The PDF file is in %BUILDDIR%/pdf.
	goto end
)
SphinxからのPDFの作成
make.bat pdf

これで、とりあえずPDFが作成できました。ただ、フォントの設定が間違っているのか、日本語が表示されませんでした。他にもいくつかwarningが出ていたので調査中です。

参考サイト

以下のサイトを参考にさせていただいました。ありがとうございました。