我正在尝试使用 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
属性,但它不包含任何字体信息。
命名样式
文件也有一个NamedStyles
属性(property)。它包含 NORMAL_TEXT
和 HEADING_1
等样式。我可以遍历所有这些并更改它们的 textStyle.weightedFontFamily
。这将是理想的解决方案,因为它将样式信息保留在它所属的位置。但是我还没有找到使用 API 更改 NamedStyles
的方法。
更深的循环
我可以继续我目前的方法,循环遍历每个 element
上的 elements
列表,保留 textStyle
中的字体以外的所有内容(其中包含诸如 bold: true
之类的内容。然而,我们目前的方法已经花费了太长时间来执行,而且这样的方法会更慢且更脆弱,所以我想避免这种情况。
最佳答案
回答:
从当前元素中提取 textStyle
并仅更改/添加 weightedFontFamily/fontFamily
对象。
代码示例:
for element in document["body"]["content"]:
if "sectionBreak" in element:
continue # Trying to change the font of a section break causes an error
textStyle = element["paragraph"]["elements"][0]["textStyle"]
textStyle["weightedFontFamily"]["fontFamily"] = "[Font name]"
requests.append(
{
"updateTextStyle": {
"range": {
"startIndex": element["startIndex"],
"endIndex": element["endIndex"],
},
"textStyle": textStyle,
"fields": "weightedFontFamily",
}
}
)
doc_service.documents().batchUpdate(
documentId=self.copy_id, body={"requests": requests}
).execute()
关于python - 使用 Google Docs API 更改整个文档的字体而不影响格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61867418/