python - 使用 Google Docs API 更改整个文档的字体而不影响格式

标签 python google-docs google-docs-api

我正在尝试使用 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_TEXTHEADING_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/

相关文章:

google-apps-script - 将 jpg 批量转换为 Google 文档

javascript - 谷歌文档阅读器 : remove the option "Open in new window"

google-docs - Google Docs API - 模拟用户文件下载

python - 如果前两个字母在 python 中重复,则替换

python - 重写写保护文件

python - Pandas 数据框隐藏索引功能?

python - 如何选择一个好的Python列表数据结构来存储每一种可能的井字棋游戏

google-docs - 使用 JavaScript 控制 Google Docs 嵌入式查看器

google-apps-script - Google App Script-表格中的文档/图像?

google-apps-script - 如何使用谷歌应用程序脚本阅读谷歌文档中的标题引用