目录中的罗马数字使用 py-docx

问题描述 投票:0回答:0

我正在尝试使用 python-docx 将以下内容添加到我的 word 文档中:

我在下面的代码中有目录的功能(和标题“目录”),但不知道如何格式化它所以它有粗体罗马数字,粗体 TOC #'s,和是 Calibri 字体:

这是我正在玩弄的代码:

from docx import Document
from docx.oxml.ns import qn
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from docx.enum.style import WD_STYLE_TYPE
from docx.shared import Pt
from docx.shared import RGBColor

# Initialising document to make word file using python

document = Document()

# Code for making Table of Contents

paragraph = document.add_paragraph()
styles = document.styles
style = styles.add_style("zzz", WD_STYLE_TYPE.CHARACTER)
style.font.name = "Monotype Corsiva"
style.font.size = Pt(18)
run = paragraph.add_run(style="zzz")


fldChar = OxmlElement('w:fldChar')  # creates a new element
fldChar.set(qn('w:fldCharType'), 'begin')  # sets attribute on element

instrText = OxmlElement('w:instrText')
instrText.set(qn('xml:space'), 'preserve')  # sets attribute on element
instrText.text = 'TOC \\o "1-3" \\h \\z \\u'   # change 1-3 depending on heading levels you need

fldChar2 = OxmlElement('w:fldChar')
fldChar2.set(qn('w:fldCharType'), 'separate')

fldChar3 = OxmlElement('w:t')
fldChar3.text = "Right-click to update field."

fldChar2.append(fldChar3)

fldChar4 = OxmlElement('w:fldChar')
fldChar4.set(qn('w:fldCharType'), 'end')

r_element = run._r
r_element.append(fldChar)
r_element.append(instrText)
r_element.append(fldChar2)
r_element.append(fldChar4)

p_element = paragraph._p

# Giving headings that need to be included in Table of contents

h = document.add_heading("")
t = h.add_run("Item 1")
title_style = h.style
title_style.font.name = "Calibri (Body)"
title_style.font.color.rgb = RGBColor(0,0,0)
rFonts = title_style.element.rPr.rFonts
rFonts.set(qn("w:asciiTheme"), "Calibri (Body)")
p = document.add_paragraph()
p.add_run("test")
document.add_heading("Item 2")

# Saving the word file by giving name to the file

name = "test toc"
document.save(name+".docx")```
python python-docx
© www.soinside.com 2019 - 2024. All rights reserved.