使用 Sphinx 撰写技术文档并生成 PDF 总结
這幾天準備編排部分翻譯的書籍和文檔,找了好些工具,最終定格在 Sphinx 上,并基于 ReadTheDocs 提供的 SaaS 服務進行分發和分享。本篇博客是對整個過程的一次記錄和總結。
項目代碼:qiwihui/sphinx-doc-starter
認識 Sphinx
Sphinx 是一個基于 Python 的文檔生成項目。最早只是用來生成 Python 的項目文檔,使用 reStructuredText 格式。但隨著項目的逐漸完善,很多非 Python 的項目也采用 Sphinx 作為文檔寫作工具,甚至完全可以用 Sphinx 來寫書。
使用 Sphinx 生成文檔的優點包括:
- 豐富的輸出格式: 支持輸出為 HTML(包括 Windows 幫助文檔),LaTeX(可以打印PDF版本), manual pages(man 文檔), 純文本等若干種格式;
- 完備的交叉引用: 語義化的標簽,并可以自動化鏈接函數、類、引文、術語等;
- 明晰的分層結構: 輕松定義文檔樹,并自動化鏈接同級/父級/下級文章;
- 美觀的自動索引: 可自動生成美觀的模塊索引;
- 精確的語法高亮: 基于 Pygments 自動生成語法高亮;
- 開放的擴展: 支持代碼塊的自動測試,自動包含 Python 的模塊自述文檔,等等。
開始
這個過程包括如下步驟:
- 安裝 Sphinx
- 第一個文檔
- 在線托管
- 生成 PDF
安裝 Sphinx
Sphinx 依賴于 Python,并提供了 Python 包,所以使用 pip 安裝既可。這里我只安裝了 sphinx-doc 這個包。
pip install sphinx-doc這時,通過 bash 自動補全(連續兩下 tab),可以看到有幾個命令,Sphinx 推薦使用 sphinx-quickstart,這是一個設置向導。
$ sphinx- sphinx-apidoc sphinx-autogen sphinx-build sphinx-quickstart設置 Sphinx
運行 sphinx-quickstart,以下主要設置項目名稱,作者名稱以及語言(zh_CN)即可,其他默認。
$ sphinx-quickstart Welcome to the Sphinx 1.8.4 quickstart utility.Please enter values for the following settings (just press Enter to accept a default value, if one is given in brackets).Selected root path: .You have two options for placing the build directory for Sphinx output. Either, you use a directory "_build" within the root path, or you separate "source" and "build" directories within the root path. > Separate source and build directories (y/n) [n]: yInside the root directory, two more directories will be created; "_templates" for custom HTML templates and "_static" for custom stylesheets and other static files. You can enter another prefix (such as ".") to replace the underscore. > Name prefix for templates and static dir [_]: The project name will occur in several places in the built documentation. > Project name: 一本書 > Author name(s): qiwihui > Project release []: 0.0.1If the documents are to be written in a language other than English, you can select a language here by its language code. Sphinx will then translate text that it generates into that language.For a list of supported codes, see http://sphinx-doc.org/config.html#confval-language. > Project language [en]: zh_CNThe file name suffix for source files. Commonly, this is either ".txt" or ".rst". Only files with this suffix are considered documents. > Source file suffix [.rst]: One document is special in that it is considered the top node of the "contents tree", that is, it is the root of the hierarchical structure of the documents. Normally, this is "index", but if your "index" document is a custom template, you can also set this to another filename. > Name of your master document (without suffix) [index]: Indicate which of the following Sphinx extensions should be enabled: > autodoc: automatically insert docstrings from modules (y/n) [n]: > doctest: automatically test code snippets in doctest blocks (y/n) [n]: > intersphinx: link between Sphinx documentation of different projects (y/n) [n]: > todo: write "todo" entries that can be shown or hidden on build (y/n) [n]: > coverage: checks for documentation coverage (y/n) [n]: > imgmath: include math, rendered as PNG or SVG images (y/n) [n]: > mathjax: include math, rendered in the browser by MathJax (y/n) [n]: > ifconfig: conditional inclusion of content based on config values (y/n) [n]: > viewcode: include links to the source code of documented Python objects (y/n) [n]: > githubpages: create .nojekyll file to publish the document on GitHub pages (y/n) [n]: A Makefile and a Windows command file can be generated for you so that you only have to run e.g. `make html` instead of invoking sphinx-build directly. > Create Makefile? (y/n) [y]: > Create Windows command file? (y/n) [y]: Creating file ./source/conf.py. Creating file ./source/index.rst. Creating file ./Makefile. Creating file ./make.bat.Finished: An initial directory structure has been created.You should now populate your master file ./source/index.rst and create other documentation source files. Use the Makefile to build the docs, like so:make builder where "builder" is one of the supported builders, e.g. html, latex or linkcheck.解釋1,整個設置過程包括:
開啟的擴展,均默認為否:
- autodoc
- doctest
- intersphinx
- todo
- coverage
- imgmath
- mathjax
- ifconfig
- viewcode
- githubpages
解釋2,項目目錄文件結構如下:
sphinx-test ├── Makefile ├── build ├── make.bat └── source├── _static├── _templates├── conf.py└── index.rst其中:
- Makefile:可以看作是一個包含指令的文件,在使用 make 命令時,可以使用這些指令來構建文檔輸出。
- build:生成的文件的輸出目錄。
- make.bat:Windows 用命令行。
- _static:靜態文件目錄,比如圖片等。
- _templates:模板目錄。
- conf.py:存放 Sphinx 的配置,包括在 sphinx-quickstart 時選中的那些值,可以自行定義其他的值。
- index.rst:文檔項目起始文件。
接下來看看默認生成的內容:
$ make html Running Sphinx v1.8.4 loading translations [zh_CN]... done making output directory... building [mo]: targets for 0 po files that are out of date building [html]: targets for 1 source files that are out of date updating environment: 1 added, 0 changed, 0 removed reading sources... [100%] index looking for now-outdated files... none found pickling environment... done checking consistency... done preparing documents... done writing output... [100%] index generating indices... genindex writing additional pages... search copying static files... done copying extra files... done dumping search index in Chinese (code: zh) ... done dumping object inventory... done build succeeded.The HTML pages are in build/html.然后直接在瀏覽器中打開 build/html/index.html 這個文件。
默認風格為 alabaster,可以改成 ReadTheDocs 的風格: sphinx_rtd_theme。
# -- Options for HTML output -------------------------------------------------# The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'sphinx_rtd_theme'
第一個文檔
我們以一下文檔為例:
This is a Title =============== That has a paragraph about a main subject and is set when the '=' is at least the same length of the title itself.Subject Subtitle ---------------- Subtitles are set with '-' and are required to have the same length of the subtitle itself, just like titles.Lists can be unnumbered like:* Item Foo* Item BarOr automatically numbered:#. Item 1#. Item 2Inline Markup ------------- Words can have *emphasis in italics* or be **bold** and you can define code samples with back quotes, like when you talk about a command: ``sudo`` gives you super user powers!將之寫入 example.rst 中,并修改 index.rst 為:
Welcome to 一本書's documentation! ==================================.. toctree:::maxdepth: 2:caption: 目錄:exampleIndices and tables ==================* :ref:`genindex` * :ref:`modindex` * :ref:`search`重新編譯,這時文檔已經改變。
在線托管
ReadTheDocs 可是直接用于托管 sphinx 生成的網頁文檔。
將之前的文檔用 Git 管理,并推送到 Github,然后在 ReadTheDocs 中 Import a Project 即可。
另外,可以設置自定義域名:
過程很簡單。
生成 PDF
Sphinx 生成 PDF 的過程先將 rst 轉換為 tex,再生產PDF。這個過程遇到了比較多的坑,最后總結下來過程如下:
首先,安裝 Tex 環境。在 Mac 上,推薦安裝 MacTex 而不是 BasicTex,對于新手來說 BasicTex 上需要自己處理很多以來問題。完成后使用 tlmgr 更新 TexLive。
$ brew cask install mactex $ sudo tlmgr update --self然后,在 con.py 中設置 latex_engine 和 latex_elements 兩個參數,同時也可以設置 latex_documents 參數來設置文檔。
latex_engine = 'xelatex' latex_elements = {'papersize': 'a4paper','pointsize': '11pt','preamble': r''' \usepackage{xeCJK} \setCJKmainfont[BoldFont=STZhongsong, ItalicFont=STKaiti]{STSong} \setCJKsansfont[BoldFont=STHeiti]{STXihei} \setCJKmonofont{STFangsong} \XeTeXlinebreaklocale "zh" \XeTeXlinebreakskip = 0pt plus 1pt \parindent 2em \definecolor{VerbatimColor}{rgb}{0.95,0.95,0.95} \setcounter{tocdepth}{3} \renewcommand\familydefault{\ttdefault} \renewcommand\CJKfamilydefault{\CJKrmdefault} ''' } # 設置文檔 latex_documents = [(master_doc, 'sphinx.tex', '你的第一本 Sphinx 書','作者:qiwihui', 'manual', True), ]最后,編譯:
$ make latexpdfmake latexpdf 會完成 rst轉換為 tex 并將 tex 生成 PDF,可以手動分開:
$ make latex $ cd build/latex $ make在 build/latex 下可以查看到生成的 PDF 文檔。
字體
使用 fc-list 來獲取字體信息,修改相應字體設置即可。
$ brew install fontconfig $ fc-list :lang=zh遇到的問題:
解決:使用 sudo tlmgr install 安裝相應的包即可。
總結
簡單過了一下整個文檔的流程,總體來說,Sphinx非常適合用來編寫項目文檔,reStructuredText 比起 Markdown 也有太多的優勢,值得推薦。
GitHub repo: qiwihui/blogFollow me: @qiwihui
Site: QIWIHUI
總結
以上是生活随笔為你收集整理的使用 Sphinx 撰写技术文档并生成 PDF 总结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java SE 12扩展Switch语句
- 下一篇: Perseus-BERT——业内性能极致