最も簡単なアプローチは、TOCをサブクラス化し、それらのafterFlowableキャッチャーをdocTemplateに追加することであると考えました。
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である程度関連しているように見せます。