使用 Sphinx 撰写技术文档并生成 PDF 总结
這幾天準(zhǔn)備編排部分翻譯的書籍和文檔,找了好些工具,最終定格在 Sphinx 上,并基于 ReadTheDocs 提供的 SaaS 服務(wù)進(jìn)行分發(fā)和分享。本篇博客是對(duì)整個(gè)過(guò)程的一次記錄和總結(jié)。
項(xiàng)目代碼:qiwihui/sphinx-doc-starter
認(rèn)識(shí) Sphinx
Sphinx 是一個(gè)基于 Python 的文檔生成項(xiàng)目。最早只是用來(lái)生成 Python 的項(xiàng)目文檔,使用 reStructuredText 格式。但隨著項(xiàng)目的逐漸完善,很多非 Python 的項(xiàng)目也采用 Sphinx 作為文檔寫作工具,甚至完全可以用 Sphinx 來(lái)寫書。
使用 Sphinx 生成文檔的優(yōu)點(diǎn)包括:
- 豐富的輸出格式: 支持輸出為 HTML(包括 Windows 幫助文檔),LaTeX(可以打印PDF版本), manual pages(man 文檔), 純文本等若干種格式;
- 完備的交叉引用: 語(yǔ)義化的標(biāo)簽,并可以自動(dòng)化鏈接函數(shù)、類、引文、術(shù)語(yǔ)等;
- 明晰的分層結(jié)構(gòu): 輕松定義文檔樹,并自動(dòng)化鏈接同級(jí)/父級(jí)/下級(jí)文章;
- 美觀的自動(dòng)索引: 可自動(dòng)生成美觀的模塊索引;
- 精確的語(yǔ)法高亮: 基于 Pygments 自動(dòng)生成語(yǔ)法高亮;
- 開放的擴(kuò)展: 支持代碼塊的自動(dòng)測(cè)試,自動(dòng)包含 Python 的模塊自述文檔,等等。
開始
這個(gè)過(guò)程包括如下步驟:
- 安裝 Sphinx
- 第一個(gè)文檔
- 在線托管
- 生成 PDF
安裝 Sphinx
Sphinx 依賴于 Python,并提供了 Python 包,所以使用 pip 安裝既可。這里我只安裝了 sphinx-doc 這個(gè)包。
pip install sphinx-doc這時(shí),通過(guò) bash 自動(dòng)補(bǔ)全(連續(xù)兩下 tab),可以看到有幾個(gè)命令,Sphinx 推薦使用 sphinx-quickstart,這是一個(gè)設(shè)置向?qū)А?/p> $ sphinx- sphinx-apidoc sphinx-autogen sphinx-build sphinx-quickstart
設(shè)置 Sphinx
運(yùn)行 sphinx-quickstart,以下主要設(shè)置項(xiàng)目名稱,作者名稱以及語(yǔ)言(zh_CN)即可,其他默認(rèn)。
$ 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,整個(gè)設(shè)置過(guò)程包括:
開啟的擴(kuò)展,均默認(rèn)為否:
- autodoc
- doctest
- intersphinx
- todo
- coverage
- imgmath
- mathjax
- ifconfig
- viewcode
- githubpages
解釋2,項(xiàng)目目錄文件結(jié)構(gòu)如下:
sphinx-test ├── Makefile ├── build ├── make.bat └── source├── _static├── _templates├── conf.py└── index.rst其中:
- Makefile:可以看作是一個(gè)包含指令的文件,在使用 make 命令時(shí),可以使用這些指令來(lái)構(gòu)建文檔輸出。
- build:生成的文件的輸出目錄。
- make.bat:Windows 用命令行。
- _static:靜態(tài)文件目錄,比如圖片等。
- _templates:模板目錄。
- conf.py:存放 Sphinx 的配置,包括在 sphinx-quickstart 時(shí)選中的那些值,可以自行定義其他的值。
- index.rst:文檔項(xiàng)目起始文件。
接下來(lái)看看默認(rèn)生成的內(nèi)容:
$ 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 這個(gè)文件。
默認(rèn)風(fēng)格為 alabaster,可以改成 ReadTheDocs 的風(fēng)格: 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'
第一個(gè)文檔
我們以一下文檔為例:
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`重新編譯,這時(shí)文檔已經(jīng)改變。
在線托管
ReadTheDocs 可是直接用于托管 sphinx 生成的網(wǎng)頁(yè)文檔。
將之前的文檔用 Git 管理,并推送到 Github,然后在 ReadTheDocs 中 Import a Project 即可。
另外,可以設(shè)置自定義域名:
過(guò)程很簡(jiǎn)單。
生成 PDF
Sphinx 生成 PDF 的過(guò)程先將 rst 轉(zhuǎn)換為 tex,再生產(chǎn)PDF。這個(gè)過(guò)程遇到了比較多的坑,最后總結(jié)下來(lái)過(guò)程如下:
首先,安裝 Tex 環(huán)境。在 Mac 上,推薦安裝 MacTex 而不是 BasicTex,對(duì)于新手來(lái)說(shuō) BasicTex 上需要自己處理很多以來(lái)問(wèn)題。完成后使用 tlmgr 更新 TexLive。
$ brew cask install mactex $ sudo tlmgr update --self然后,在 con.py 中設(shè)置 latex_engine 和 latex_elements 兩個(gè)參數(shù),同時(shí)也可以設(shè)置 latex_documents 參數(shù)來(lái)設(shè)置文檔。
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} ''' } # 設(shè)置文檔 latex_documents = [(master_doc, 'sphinx.tex', '你的第一本 Sphinx 書','作者:qiwihui', 'manual', True), ]最后,編譯:
$ make latexpdfmake latexpdf 會(huì)完成 rst轉(zhuǎn)換為 tex 并將 tex 生成 PDF,可以手動(dòng)分開:
$ make latex $ cd build/latex $ make在 build/latex 下可以查看到生成的 PDF 文檔。
字體
使用 fc-list 來(lái)獲取字體信息,修改相應(yīng)字體設(shè)置即可。
$ brew install fontconfig $ fc-list :lang=zh遇到的問(wèn)題:
解決:使用 sudo tlmgr install 安裝相應(yīng)的包即可。
總結(jié)
簡(jiǎn)單過(guò)了一下整個(gè)文檔的流程,總體來(lái)說(shuō),Sphinx非常適合用來(lái)編寫項(xiàng)目文檔,reStructuredText 比起 Markdown 也有太多的優(yōu)勢(shì),值得推薦。
GitHub repo: qiwihui/blogFollow me: @qiwihui
Site: QIWIHUI
總結(jié)
以上是生活随笔為你收集整理的使用 Sphinx 撰写技术文档并生成 PDF 总结的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Java SE 12扩展Switch语句
- 下一篇: Perseus-BERT——业内性能极致