我正在尝试使用API更改整个Google文档的字体。目的是让我们的应用程序用户使用其公司的字体导出文档。
这是我目前正在做的事情:
from googleapiclient.discovery import build
doc_service = build("docs", "v1")
document = self.doc_service.documents().get(documentId="[Document ID]").execute()
requests = []
for element in document["body"]["content"]:
if "sectionBreak" in element:
continue # Trying to change the font of a section break causes an error
requests.append(
{
"updateTextStyle": {
"range": {
"startIndex": element["startIndex"],
"endIndex": element["endIndex"],
},
"textStyle": {
"weightedFontFamily": {
"fontFamily": "[Font name]"
},
},
"fields": "weightedFontFamily",
}
}
)
doc_service.documents().batchUpdate(
documentId=self.copy_id, body={"requests": requests}
).execute()
上面的代码更改了字体,但由于它覆盖了元素的整个样式,因此它也删除了任何粗体文本格式。我研究过的一些选项:
DocumentStyle
文档具有DocumentStyle
属性,但不包含任何字体信息。
DocumentStyle
文档也具有NamedStyles
属性。它包含NamedStyles
和NamedStyles
之类的样式。我可以遍历所有这些内容并更改其NORMAL_TEXT
。这将是理想的解决方案,因为它将样式信息保留在其所属位置。但是我还没有找到使用API更改HEADING_1
的方法。
我可以继续我当前的方法,遍历每个textStyle.weightedFontFamily
上的NamedStyles
列表,保留elements
中除字体之外的所有内容(其中包含element
之类的内容)。但是,我们当前的方法执行起来已经花费了很长时间,并且这种方法既慢又脆弱,因此我想避免这种情况。
从当前元素中提取textStyle
,仅更改/添加bold: true
对象。
textStyle
希望对您有帮助!