使用rst2pdf实现将sphinx生成PDF


Posted in Python onJune 07, 2016

当初项目文档是用sphinx写的,一套rst下来make html得到一整个漂亮的在线文档。现在想要将文档导出为离线的handbook pdf,于是找到了rst2pdf这个项目,作为sphinx的拓展,然后加上少量配置即可输出中文PDF。

rst2pdf

简介

使用rst2pdf实现将sphinx生成PDF

rst2pdf是一个将 reStructuredText 转换为 PDF 的工具,具有下列特性:

  1. 自定义页面布局
  2. 支持层叠样式表
  3. 支持内嵌TTF和Type1字体
  4. 支持几乎所有语言的语法高亮
  5. 使用reStructuredText作为源文件
  6. 支持字间距调整

安装

easy_install rst2pdf

配置rst2pdf

注册到sphinx项目

需要告诉sphinx我们安装了rst2pdf,并且将其作为插件使用。只需在项目根目录下的conf.py中配置:

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
  'sphinx.ext.autodoc',
  'rst2pdf.pdfbuilder'
]

即可。然后,在conf.py中拷入PDF相关的配置:

# -- 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'HanLP Handbook', u'HanLP Handbook', u'hankcs'),
]
 
# A comma-separated list of custom stylesheets. Example:
pdf_stylesheets = ['a3','zh_CN']
 
# 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 = "zh_CN"
 
# 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
 
# Enable rst2pdf extension modules (default is only vectorpdf)
# you need vectorpdf if you want to use sphinx's graphviz support
#pdf_extensions = ['vectorpdf']
 
# Page template name for "regular" pages
#pdf_page_template = 'cutePage'
 
# Show Table Of Contents at the beginning?
# pdf_use_toc = False
 
# How many levels deep should the table of contents be?
pdf_toc_depth = 2
 
# Add section number to section references
pdf_use_numbered_links = False
 
# Background images fitting mode
pdf_fit_background_mode = 'scale'

具体配置项的值请自行调整,不需要严格按照我的来。

样式表

在项目根目录下创建一个zh_CN.json,写入:

{
 "embeddedFonts": [
  "simsun.ttc"
 ],
 "fontsAlias": {
  "stdFont": "simsun",
  "stdBold": "simsun",
  "stdItalic": "simsun",
  "stdBoldItalic": "simsun",
  "stdMono": "simsun",
  "stdMonoBold": "simsun",
  "stdMonoItalic": "simsun",
  "stdMonoBoldItalic": "simsun",
  "stdSans": "simsun",
  "stdSansBold": "simsun",
  "stdSansItalic": "simsun",
  "stdSansBoldItalic": "simsun"
 },
 "styles": [
  [
   "base",
   {
    "wordWrap": "CJK"
   }
  ],
  [
   "literal",
   {
    "wordWrap": "None"
   }
  ]
 ]
}

关于以上样式的说明:

embeddedFonts用于嵌入字体,经试验,必须包含至少四个值才不会报错。不过这四个字体值可以是重复的。

fontsAlias用来指定各类字形用什么字体。如stdFont指正文字体,stdBold指粗体,stdItalic指斜体。其他的还有stdBoldItalic粗斜体,stdMono等宽体,等等。确保所用字体已经安装在你的操作系统上,且字体必须是TTF类型的(Windows环境下限制比较多~)。

wordWrap用于指定换行规则,CJK就是适用于中日韩文字的规则。这是从网上的模板抄来的,但经我的测试发现,如果用CJK规则的话,中英混排的文档里面英文部分就没法正常断行,这真是个遗憾。实际上,fontsAlias的分类很多都只对英文字体有意义,如严格来讲中文是没有所谓斜体的(不过因为Word的普及,经常看到中文被设置为斜体的情形)。如果是纯中文文档,当然随便用哪些中文字体都行,如宋体。现实中,经常会有中英文混排的情形,所以如果全用中文字体的话,英文部分就没法显示斜体等字形了。

关于pdf_stylesheets的说明:这个参数中默认使用的某些样式包含了一些字体,而这些字体并非在所有操作系统上都找得到。'sphinx'和'kerning'都是默认提供的样式,要么不用它们,要么直接修改其包含的字体。'a4'指设置输出的PDF为A4纸大小。默认的样式文件可以在rst2pdf的安装路径下找到。

然后配置编译脚本

Windows用户,在make.bat中加入:

if "%1" == "pdf" (
  %SPHINXBUILD% -b pdf %ALLSPHINXOPTS% %BUILDDIR%/pdf
  if errorlevel 1 exit /b 1
  echo.
  echo.Build finished. The pdf files are in %BUILDDIR%/pdf.
  goto end
)

类Unix用户修改Makefile:

pdf:
  $(SPHINXBUILD) -b pdf $(ALLSPHINXOPTS) $(BUILDDIR)/pdf
  @echo
  @echo "Build finished. The PDF files are in _build/pdf."

输出PDF

然后一句:

make pdf

就能输出PDF了。

解决findfonts.py:249 Unknown font:

这应该是由于pdf_font_path配置有误造成的,事实上,我确定配置无误rst2pdf还是找不到字体文件,于是我修改了X:\Program Files (x86)\Python27\Lib\site-packages\rst2pdf\findfonts.py第236行,在

fontfile = get_nt_fname(fname)

后面加了一句:

fontfile = 'C:\\Windows\\Fonts\\simsun.ttc'

强行解决问题。

解决rst2pdf输出PDF为空白文档

事实上,在字体正常的情况下,我发现输出的PDF依然是空白的:

使用rst2pdf实现将sphinx生成PDF

在使用二分法排除rst文件中的问题后,我发现这是由于PDF开头的目录造成的。当目录超出一页时就会发生这种情况,我倾向于认为这是rst2pdf的一个bug。

解决方法是将pdf_toc_depth调小一点,或者干脆不生成目录,pdf_use_toc = False。

PDF效果

于是再次重试,可以生成漂亮的PDF了:

使用rst2pdf实现将sphinx生成PDF

相关链接:

http://sphinx-users.jp/cookbook/pdf/rst2pdf.html

http://ralsina.me/static/manual.pdf

http://www.typemylife.com/sphinx-restructuredtext-pdf-generation-with-rst2pdf/

Python 相关文章推荐
用Python编写一个每天都在系统下新建一个文件夹的脚本
May 04 Python
python之文件的读写和文件目录以及文件夹的操作实现代码
Aug 28 Python
Python heapq使用详解及实例代码
Jan 25 Python
机器学习之KNN算法原理及Python实现方法详解
Jul 09 Python
浅谈django的render函数的参数问题
Oct 16 Python
python实现向微信用户发送每日一句 python实现微信聊天机器人
Mar 27 Python
Python实现直方图均衡基本原理解析
Aug 08 Python
python 调试冷知识(小结)
Nov 11 Python
使用Pytorch来拟合函数方式
Jan 14 Python
matplotlib事件处理基础(事件绑定、事件属性)
Feb 03 Python
教你使用Python pypinyin库实现汉字转拼音
May 27 Python
如何使用PyCharm及常用配置详解
Jun 03 Python
python监控文件或目录变化
Jun 07 #Python
浅析Python中的多条件排序实现
Jun 07 #Python
Python卸载模块的方法汇总
Jun 07 #Python
Python运行报错UnicodeDecodeError的解决方法
Jun 07 #Python
PyCharm使用教程之搭建Python开发环境
Jun 07 #Python
Python使用Pycrypto库进行RSA加密的方法详解
Jun 06 #Python
Python的Flask框架应用调用Redis队列数据的方法
Jun 06 #Python
You might like
PHP 批量删除 sql语句
2009/06/05 PHP
php开发环境配置记录
2011/01/14 PHP
分享PHP header函数使用教程
2013/09/05 PHP
php中preg_replace正则替换用法分析【一次替换多个值】
2017/01/17 PHP
Laravel5.1 框架控制器基础用法实例分析
2020/01/04 PHP
JQuery 获取和设置Select选项的代码
2010/02/07 Javascript
Json字符串转换为JS对象的高效方法实例
2013/05/01 Javascript
css结合js制作下拉菜单示例代码
2014/02/27 Javascript
Jquery $when done then的用法详解
2016/05/20 Javascript
浅谈bootstrap源码分析之tab(选项卡)
2016/06/06 Javascript
ionic js 复选框 与普通的 HTML 复选框到底有没区别
2016/06/06 Javascript
BootStrap 智能表单实战系列(五) 表单依赖插件处理
2016/06/13 Javascript
JavaScript动态添加css样式和script标签
2016/07/19 Javascript
Vuejs第九篇之组件作用域及props数据传递实例详解
2016/09/05 Javascript
微信小程序-拍照或选择图片并上传文件
2017/01/06 Javascript
JS中使用正则表达式g模式和非g模式的区别
2017/04/01 Javascript
jQuery动态移除与增加onclick属性的方法详解
2018/06/07 jQuery
基于element-ui组件手动实现单选和上传功能
2018/12/06 Javascript
微信小程序 弹窗输入组件的实现解析
2019/08/12 Javascript
微信小程序 点击切换样式scroll-view实现代码实例
2019/10/11 Javascript
梳理一下vue中的生命周期
2020/12/30 Vue.js
[02:19]2014DOTA2国际邀请赛 专访820少年们一起去追梦吧
2014/07/14 DOTA
[33:42]LGD vs OG 2018国际邀请赛小组赛BO2 第一场 8.16
2018/08/17 DOTA
[47:50]Secret vs VP 2018国际邀请赛小组赛BO2 第二场 8.17
2018/08/20 DOTA
[34:47]完美世界DOTA2联赛PWL S2 Magma vs LBZS 第一场 11.18
2020/11/18 DOTA
解决新django中的path不能使用正则表达式的问题
2018/12/18 Python
python类的实例化问题解决
2019/08/31 Python
tensorflow如何继续训练之前保存的模型实例
2020/01/21 Python
Python3使用tesserocr识别字母数字验证码的实现
2021/01/29 Python
CSS3中的@keyframes关键帧动画的选择器绑定
2016/06/13 HTML / CSS
Fairyseason:为个人和批发商提供女装和配件
2017/03/01 全球购物
华硕新加坡官方网上商店:ASUS Singapore
2020/07/09 全球购物
应用艺术毕业生的自我评价
2013/12/04 职场文书
2015年度高中教师工作总结
2015/05/26 职场文书
军训心得体会范文(2016最新篇)
2016/01/11 职场文书
Python Matplotlib绘制条形图的全过程
2021/10/24 Python