我是最新的reportlab和django,并且带有“TOCEntry”通知的标准鸭嘴兽TOC非常适合我的文档。
我现在尝试在目录中添加另外 2 个部分:“图表列表”和“表格列表”。由于文档中的可流动 h1、h2、表格、图像等可以以任何顺序出现,因此我似乎无法将这两个列表与主目录分开。理想情况下,我想要这样的东西:
Table of Content:
Heading1
Sub1
Sub2
Heading2
Sub3
Sub4
Sub5
List of Figures:
Figure1
Figure2
List of Tables:
Table1
Table2
据我了解,“TOCEntry”是查找的标签,使用 AfterFlowable 最终会将所有可流动的内容按照实际文档中所示的相同顺序放置。这不是我想要的。任何让 TOC 看起来有点像上面的描述的指示都将受到高度赞赏。
我认为最简单的方法是子类化 TOC,并在 docTemplate 中为它们添加 afterFlowable 捕获器。
class MyDocTemplate(BaseDocTemplate):
def __init__(self, filename, **kw):
self.allowSplitting = 0
apply(BaseDocTemplate.__init__, (self, filename), kw)
template = PageTemplate('normal', [Frame(1*inch, 1*inch, 6.5*inch, 9.5*inch, id='F1')])
self.addPageTemplates(template)
def afterFlowable(self, flowable):
"Registers TOC entries."
if flowable.__class__.__name__ == 'Paragraph':
text = flowable.getPlainText()
style = flowable.style.name
if style == 'reportHeading1':
toc_el = [ 0, text, self.page ] # basic elements
toc_bm = getattr(flowable, '_bookmarkName', None) # bookmark for links
if toc_bm:
toc_el.append( toc_bm )
self.notify('TOCEntry', tuple(toc_el) )
elif style == 'reportHeading2':
toc_el = [ 1, text, self.page ] # basic elements
toc_bm = getattr(flowable, '_bookmarkName', None) # bookmark for links
if toc_bm:
toc_el.append( toc_bm )
self.notify('TOCEntry', tuple(toc_el) )
elif style == 'TableTitleStyle':
toc_el = [ 1, text, self.page ] # basic elements
toc_bm = getattr(flowable, '_bookmarkName', None) # bookmark for links
if toc_bm:
toc_el.append( toc_bm )
self.notify('TOCTable', tuple(toc_el) )
elif style == 'GraphicTitleStyle':
toc_el = [ 1, text, self.page ] # basic elements
toc_bm = getattr(flowable, '_bookmarkName', None) # bookmark for links
if toc_bm:
toc_el.append( toc_bm )
self.notify('TOCFigure', tuple(toc_el) )
图表的辅助目录:
class ListOfFigures(TableOfContents):
def notify(self, kind, stuff):
""" The notification hook called to register all kinds of events.
Here we are interested in 'Figure' events only.
"""
if kind == 'TOCFigure':
self.addEntry(*stuff)
class ListOfTables(TableOfContents):
def notify(self, kind, stuff):
""" The notification hook called to register all kinds of events.
Here we are interested in 'Table' events only.
"""
if kind == 'TOCTable':
self.addEntry(*stuff)
最后是文档生成过程。我会在标准目录之后添加 ListOfTables 和 ListOfFigures 的实例,使其看起来像它们在实际的 pdf 中有些相关。
在尝试自己解决这个问题后,我找到了一个更简单的 Priyeshj 响应解决方案。无需子类化 TOC 类,您只需在创建 tableoffigures 类和 tableoftables 实例时设置它的 self._notifyKind 参数即可。
它是这样完成的:
toc = TableOfContents()
toc_figures = TableOfContents(notifyKind = 'TOCFigure')
toc_tables = TableOfContents(notifyKind = 'TOCTable')