Created
November 21, 2018 10:02
-
-
Save GaryLee/f456c828c5bc841720af883bfdb661ff to your computer and use it in GitHub Desktop.
Add hyperlinks to the word which match the bookmark in Word document.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!python | |
# coding: utf-8 | |
import os | |
import win32com.client | |
class PostProcedure(object): | |
def __init__(self): | |
pass | |
def attach(self): | |
self.wordApp = win32com.client.Dispatch("Word.Application") | |
self.wordApp.Visible = True | |
self.doc = self.wordApp.ActiveDocument | |
print(os.path.basename(self.doc.FullName)) | |
def extractBookmarks(self): | |
bookmarks = {} | |
for bookmark in self.doc.Bookmarks: | |
# print("{}".format(bookmark.Name)) | |
bookmarks[bookmark.Name] = 0 | |
return bookmarks | |
def taskAddBookmarkForRegisters(self): | |
bookmarks = self.extractBookmarks() | |
for para in self.doc.Paragraphs: | |
for word in para.Range.Words: | |
text = word.Text.strip() | |
if text in bookmarks: | |
#print("{}:{} (Bookmarks: {}, Hyperlinks: {})".format(word.Start, word.End, word.Bookmarks.Count, word.Hyperlinks.Count)) | |
if word.Bookmarks.Count == 0 and word.Hyperlinks.Count == 0: | |
bookmarks[text] += 1 | |
print("\t\tAdd bookmark: {}; count={}".format(word.Text, bookmarks[text])) | |
self.doc.Hyperlinks.Add(Anchor=word, Address="#{}".format(text)) | |
def run(self): | |
"""Execute all methods leading with keyword 'task' in this class.""" | |
self.attach() | |
# print('\n'.join(dir(self.doc))) | |
for name in self.__dir__(): | |
attr = getattr(self, name) | |
if name.startswith('task') and callable(attr): | |
attr() | |
#self.doc.save(self.filename_out) | |
def main(): | |
postproc = PostProcedure() | |
postproc.run() | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment