I am trying to add bookmark to a cell in an existing table and want to create the hyperlink in a separate page.
I have seen a tutorial on how to create a bookmark and hyperlink but only to a run here: how to create bookmarks in a word document, then create internal hyperlinks to the bookmark w/ python
Below is my code, when run it successfully created the file. But when I open the file cannot be opened as it gives out an error.
Not sure though if my code is correct. I grabbed them from all over the internet trying which one would work. Appreciate if anyone can point to the right direction. Just started learning python and programming in general
from docx import Document
from docx.oxml.ns import qn
from docx.oxml.shared import OxmlElement
document = Document("sample rows.docx")
table = document.tables[0]
rows = table.rows
xml_cell = rows[1].cells[0]._tc
start = OxmlElement('w:bookmarkStart')
start.set(qn('w:id'), 'row1')
start.set(qn('w:name'), 'row1')
start.set(qn('w:colFirst'), '0')
start.set(qn('w:colLast'), '0')
xml_cell.append(start)
end = OxmlElement('w:bookmarkEnd')
end.set(qn('w:id'), 'row1')
end.set(qn('w:name'), 'row1')
xml_cell.append(end)
# Adding new page and table
document.add_page_break()
new_table = document.add_table(1, 1)
cell = new_table.add_row().cells[0]
cell.text = "This is row 1 link"
c_tc = cell._tc
hyperlink = OxmlElement('w:hyperlink')
hyperlink.set(qn('w:anchor'), 'row1')
c_tc.append(hyperlink)
document.save("sample rows1.docx")
Update: I reverted to using run in my bookmark by extracting it form inside the cell as I was not able to find solution to adding bookmark to a cell. I will still put out the question above in the hopes that somebody will answer. The below code works for me (not related to the above code).
def add_bookmark(self, run, title_id):
run_tag = run._r
# create start bookmark
start = OxmlElement('w:bookmarkStart')
start.set(qn('w:id'), f'{title_id}')
start.set(qn('w:name'), f'{title_id}')
run_tag.append(start)
text = OxmlElement('w:r')
text.text = ''
run_tag.append(text)
# create end bookmark
end = OxmlElement('w:bookmarkEnd')
end.set(qn('w:id'), f'{title_id}')
run_tag.append(end)
def add_hyperlink(self, title_id, paragraph):
hyperlink = OxmlElement('w:hyperlink')
hyperlink.set(qn('w:anchor'), f'{title_id}')
new_run = OxmlElement('w:r')
rPr = OxmlElement('w:rPr')
new_run.append(rPr)
new_run.text = f"<Title>"
hyperlink.append(new_run)
r = paragraph.add_run()
r._r.append(hyperlink)
r.font.name = "Calibri"
r.font.italic = True
r.font.color.theme_color = MSO_THEME_COLOR_INDEX.HYPERLINK
r.font.underline = True