在python docx中,可以通过使用
Rich Text
造型。您应该为模板中需要样式化的特定字符/字符串在字符/字符串的位置提供一个上下文变量。此变量映射到
RichText
具有样式定义(在代码中定义)的对象,用于设置字符/字符串的样式。为了使事情更清楚,考虑一个包含以下文本的示例模板doc“test.docx”:
你好r上下文!
这个
{{..}}
是jinja2标记语法和
{{r
是重写字符样式的richtext标记。这个
context_var
是一个将样式映射到字符串的变量。
我们实现了这样的富文本样式:
from docxtpl import DocxTemplate, RichText
doc = DocxTemplate("test.docx")
rt = RichText() #create a RichText object
rt.add('World', bold=True) #pass the text as an argument and the style, bold=True
context = { 'context_var': rt } #add context variable to the context and map it to rt
doc.render(context) #render the context
doc.save("generated_doc.docx") #save as a new document
让我们看一下“generated_doc.docx”的内容:
你好
世界
!
我不知道你的模板是如何设计的,但是如果你只是想
book_title
作为粗体,模板“test.docx”的文本应如下所示:
题目:
{{r book_title_var}}
代码应修改为:
book_title = "Lord of the Rings" #or wherever you get the book title from
rt.add(book_title, bold=True)
context = { 'book_title_var': rt }
生成的文档:
题目:
指环王