Skip to content

Instantly share code, notes, and snippets.

@yangchenyun
Created April 20, 2023 07:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yangchenyun/75a0970a8a04046b528ec71b16ca9201 to your computer and use it in GitHub Desktop.
Save yangchenyun/75a0970a8a04046b528ec71b16ca9201 to your computer and use it in GitHub Desktop.
random_tools
"""
Add bookmarks to PDF files.
"""
import sys
import os
from apryse_sdk import *
LICENCE = os.environ["apryse_licence"]
PDFNet.Initialize(LICENCE)
def PrintIndent(item):
indent = item.GetIndent() - 1
i = 0
while i < indent:
sys.stdout.write(" ")
i = i + 1
def PrintOutlineTree (item):
while item.IsValid():
PrintIndent(item)
if item.IsOpen():
sys.stdout.write("- " + item.GetTitle() + " ACTION -> ")
else:
sys.stdout.write("+ " + item.GetTitle() + " ACTION -> ")
if item.HasChildren():
PrintOutlineTree(item.GetFirstChild())
item = item.GetNext()
doc = PDFDoc("example.pdf")
def create_bm(doc, offset=0, title="", page=0):
myitem = Bookmark.Create(doc, title)
myitem.SetAction(Action.CreateGoto(Destination.CreateFit(doc.GetPage(page+offset))))
doc.AddRootBookmark(myitem)
OFFSET = 16
toc = [
{'title': 'Part I: Highlights of Linear Algebra', 'page': 1},
]
for bm in toc:
create_bm(doc, offset=OFFSET, **bm)
root = doc.GetFirstBookmark()
PrintOutlineTree(root)
doc.Save("edited.pdf", SDFDoc.e_linearized)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment