0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ページ番号決め打ちで目次を作成する

Last updated at Posted at 2021-09-03

すべてreportlabで組版した場合の目次生成方法は公式サンプルがありますが、手元のpdfファイルをベースに(ページ番号決め打ちで)目次を生成するサンプルは見つけられなかった。TableOfContentsのソースを読んだ限りでは以下のようなやり方でできるらしい。table_of_contents.beforeBuild()とかいう明らかに内部向けっぽい関数を呼ぶのがポイントです。

from reportlab.pdfbase.cidfonts import UnicodeCIDFont
from reportlab.pdfbase import pdfmetrics
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.platypus.tableofcontents import TableOfContents
from reportlab.lib.pagesizes import A4

doc = SimpleDocTemplate('toc.pdf', pagesize=A4)
fontname_g = 'HeiseiMin-W3'
pdfmetrics.registerFont(UnicodeCIDFont(fontname_g))
elements = []

style=ParagraphStyle(
	name='Normal',
	fontName=fontname_g,
	fontSize=10,
)
elements.append(Paragraph("header", style))
elements.append(Spacer(10,10))

table_of_contents = TableOfContents()
table_of_contents.dotsMinLevel = 0
table_of_contents.levelStyles = [style]
# 
table_of_contents.addEntry(0, 'chapter1', 1, key=None)
table_of_contents.addEntry(0, 'chapter2', 11, key=None)
table_of_contents.beforeBuild()
elements.append(table_of_contents)

doc.build(elements)

勿論、「手元のpdf」にページ番号を振らないと本末転倒なのでご注意を…。https://qiita.com/achiwa912/items/9d82484183e3b6c9da3c のようなやり方でできます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?