Python编程实践:如何使用rst2pdf将sphinx生成PDF
来自:新开发者(IT开发者)
在Python编程实践中,当初项目文档是用sphinx写的,一套rst下来make html得到一整个漂亮的在线文档。现在想要将文档导出为离线的handbook pdf,于是找到了rst2pdf这个项目,作为sphinx的拓展,然后加上少量配置即可输出中文PDF。希望对大家学习Python编程实践有所帮助。
rst2pdf
简介
rst2pdf是一个将 reStructuredText 转换为 PDF 的工具,具有下列特性:
1.自定义页面布局
2.支持层叠样式表
3.支持内嵌TTF和Type1字体
4.支持几乎所有语言的语法高亮
5.使用reStructuredText作为源文件
6.支持字间距调整
安装
easy_install rst2pdf
配置rst2pdf
注册到sphinx项目
需要告诉sphinx我们安装了rst2pdf,并且将其作为插件使用。只需在项目根目录下的conf.py中配置:
#AddanySphinxextensionmodulenameshere,asstrings.Theycanbe #extensionscomingwithSphinx(named'sphinx.ext.*')oryourcustom #ones. extensions=[ 'sphinx.ext.autodoc', 'rst2pdf.pdfbuilder' ]
即可。然后,在conf.py中拷入PDF相关的配置:
#--OptionsforPDFoutput-------------------------------------------------- #GroupingthedocumenttreeintoPDFfiles.Listoftuples #(sourcestartfile,targetname,title,author,options). # #Ifthereismorethanoneauthor,separatethemwith\\. #Forexample:r'GuidovanRossum\\FredL.Drake,Jr.,editor' # #Theoptionselementisadictionarythatletsyouoverride #thisconfigper-document. #Forexample, #('index',u'MyProject',u'MyProject',u'AuthorName', #dict(pdf_compressed=True)) #wouldmeanthatspecificdocumentwouldbecompressed #regardlessoftheglobalpdf_compressedsetting. pdf_documents=[ ('index',u'HanLPHandbook',u'HanLPHandbook',u'hankcs'), ] #Acomma-separatedlistofcustomstylesheets.Example: pdf_stylesheets=['a3','zh_CN'] #CreateacompressedPDF #UseTrue/Falseor1/0 #Example:compressed=True #pdf_compressed=False #Acolon-separatedlistoffolderstosearchforfonts.Example: pdf_font_path=['C:\\Windows\\Fonts'] #Languagetobeusedforhyphenationsupport pdf_language="zh_CN" #Modeforliteralblockswiderthanthe<d>frame</d>.Canbe #overflow,shrinkortruncate pdf_fit_mode="shrink" #Sectionlevelthatforcesabreakpage. #Forexample:1meanstop-levelsectionsstartinanewpage #0meansdisabled #pdf_break_level=0 #Whenasectionstartsinanewpage,forceittobe'even','odd', #orjustuse'any' #pdf_breakside='any' #Insertfootnoteswheretheyaredefinedinsteadof #attheend. #pdf_inline_footnotes=True #verbositylevel.01or2 #pdf_verbosity=0 #Iffalse,noindexisgenerated. #pdf_use_index=True #Iffalse,nomodindexisgenerated. #pdf_use_modindex=True #Iffalse,nocoverpageisgenerated. #pdf_use_coverpage=True #Documentstoappendasanappendixtoallmanuals. #pdf_appendices=[] #Enableexperimentalfeaturetosplittablecells.Useit #ifyouget"DelayedTabletoobig"errors #pdf_splittables=False #SetthedefaultDPIforimages #pdf_default_dpi=72 #Enablerst2pdfextensionmodules(defaultisonlyvectorpdf) #youneedvectorpdfifyouwanttousesphinx'sgraphvizsupport #pdf_extensions=['vectorpdf'] #Pagetemplatenamefor"regular"pages #pdf_page_template='cutePage' #ShowTableOfContentsatthebeginning"alt="使用rst2pdf实现将sphinx生成PDF"/> <preclass="brush:js;">{ "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" } ] ] } </pre>
关于以上样式的说明:
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%-bpdf%ALLSPHINXOPTS%%BUILDDIR%/pdf iferrorlevel1exit/b1 echo. echo.Buildfinished.Thepdffilesarein%BUILDDIR%/pdf. gotoend )
类Unix用户修改Makefile:
pdf: $(SPHINXBUILD)-bpdf$(ALLSPHINXOPTS)$(BUILDDIR)/pdf @echo @echo"Buildfinished.ThePDFfilesarein_build/pdf."
输出PDF
然后一句:
makepdf
就能输出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依然是空白的:

在使用二分法排除rst文件中的问题后,我发现这是由于PDF开头的目录造成的。当目录超出一页时就会发生这种情况,我倾向于认为这是rst2pdf的一个bug。
解决方法是将pdf_toc_depth调小一点,或者干脆不生成目录,pdf_use_toc = False。
PDF效果
于是再次重试,可以生成漂亮的PDF了:

本文由职坐标整理并发布,了解更多内容,请关注职坐标编程语言Python频道!
你的回复
回复请先 登录 , 或 注册相关内容推荐
最新讨论 ( 更多 )
- 【资讯】十多年来,使用过C ++、Ruby、Java语言等多种语言开... (新开发者)
- 学术访谈招募 (废墟上的阅读者)
- 5分钟教会你,QML如何通过WebSocket和C++语言交互? (新开发者)
- 人工智能前沿学生论坛60期| 知识图谱专场 (Jarvis)
- Python 实现曲线点抽稀算法 (新开发者)