Advertisement
tubbadu

concatenate PDFs with bookmarks

Feb 5th, 2022
497
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.44 KB | None | 0 0
  1. #!/usr/bin/python3
  2.  
  3.  
  4. import sys, os, subprocess
  5.  
  6. def bash(cmd, read=False):
  7.     if read:
  8.         try:
  9.             x = subprocess.check_output(cmd, shell=True).decode("utf-8")
  10.         except:
  11.             x = False
  12.         return x
  13.     else:
  14.         os.system(cmd)
  15.         return
  16.  
  17. def addBookmark(title, level, pageNumber):
  18.     ret = f"BookmarkBegin\nBookmarkTitle: {title}\nBookmarkLevel: {level}\nBookmarkPageNumber: {pageNumber}\n"
  19.     return ret
  20.  
  21. def extractBookmarks(filename):
  22.     return bash(f"pdftk '{filename}' data_dump", read=True)
  23.  
  24. def merge(first, second):
  25.     # add a bookmark to the second.pdf and create second.bookmarked.pdf
  26.     secondBookmarkedData = addBookmark(second.split("/")[-1][:-4], 1, 1) + extractBookmarks(second)
  27.     with open("addBookmark.bookmarks", "w") as bookmarks:
  28.         bookmarks.write(secondBookmarkedData)
  29.     bash(f"pdftk '{second}' update_info 'addBookmark.bookmarks' output '{second}.bookmark.pdf'")
  30.     # merge pdf1 and pdf2 into final.pdf
  31.     bash(f"pdftk '{first}' '{second}.bookmark.pdf' cat output '{first}.2.pdf'")
  32.     bash(f"mv '{first}' ~/.local/share/Trash/ && mv '{first}.2.pdf' '{first}' && mv '{second}.bookmark.pdf' ~/.local/share/Trash/")
  33.     bash(f"mv 'addBookmark.bookmarks' ~/.local/share/Trash/ ")
  34.  
  35. def main():
  36.     first = sys.argv[1]
  37.     second = sys.argv[2]
  38.     merge(first, second)
  39.     if(len(sys.argv) > 3):
  40.         for arg in sys.argv[3:]:
  41.             merge(first, arg)
  42.        
  43.  
  44. if __name__ == '__main__':
  45.     main()
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement