Create outlines/TOC for existing PDF in Python

自古美人都是妖i 提交于 2020-07-05 03:29:28

问题


I'm using pyPdf to merge several PDF files into one. This works great, but I would also need to add a table of contents/outlines/bookmarks to the PDF file that is generated.

pyPdf seems to have only read support for outlines. Reportlab would allow me to create them, but the opensource version does not support loading PDF files, so that doesn't work to add outlines to an existing file.

Is there any way I can add outlines to an existing PDF using Python, or any library that would allow that?


回答1:


We had a similar problem in WeasyPrint: cairo produces the PDF files but does not support bookmarks/outlines or hyperlinks. In the end we bit the bullet, read the PDF spec, and did it ourselves.

WeasyPrint’s pdf.py has a simple PDF parser and writer that can add/override PDF "objects" to an existing documents. It uses the PDF "update" mechanism and only append at the end of the file.

This module was made for internal use only but I’m open to refactoring it to make it easier to use in other projects.

However the parser takes a few shortcuts and can not parse all valid PDF files. It may need to be adapted if PyPDF’s output is not as nice as cairo’s. From the module’s docstring:

Rather than trying to parse any valid PDF, we make some assumptions that hold for cairo in order to simplify the code:

  • All newlines are '\n', not '\r' or '\r\n'
  • Except for number 0 (which is always free) there is no "free" object.
  • Most white space separators are made of a single 0x20 space.
  • Indirect dictionary objects do not contain '>>' at the start of a line except to mark the end of the object, followed by 'endobj'. (In other words, '>>' markers for sub-dictionaries are indented.)
  • The Page Tree is flat: all kids of the root page node are page objects, not page tree nodes.



回答2:


https://github.com/yutayamamoto/pdfoutline I made a python library just for adding an outline to an existing PDF file.




回答3:


It looks like PyPDF2 can do the job. See the addBookmark method in the documentation: https://pythonhosted.org/PyPDF2/PdfFileMerger.html



来源:https://stackoverflow.com/questions/6157456/create-outlines-toc-for-existing-pdf-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!