在不影响使用Google Docs API格式的情况下更改整个文档的字体

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

我正在尝试使用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属性。它包含NamedStylesNamedStyles之类的样式。我可以遍历所有这些内容并更改其NORMAL_TEXT。这将是理想的解决方案,因为它将样式信息保留在其所属位置。但是我还没有找到使用API​​更改HEADING_1的方法。

更深循环

我可以继续我当前的方法,遍历每个textStyle.weightedFontFamily上的NamedStyles列表,保留elements中除字体之外的所有内容(其中包含element之类的内容)。但是,我们当前的方法执行起来已经花费了很长时间,并且这种方法既慢又脆弱,因此我想避免这种情况。

python google-docs google-docs-api
1个回答
1
投票

答案:

从当前元素中提取textStyle,仅更改/添加bold: true对象。

代码示例:

textStyle

希望对您有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.