【问题标题】:Changing text attributes (font, size, etc) at the cursor level in a google doc using Google apps script使用谷歌应用脚​​本在谷歌文档中更改光标级别的文本属性(字体、大小等)
【发布时间】:2014-09-02 12:55:04
【问题描述】:

我想知道是否以及如何在光标级别更改 Google Apps 脚本中的字体、大小等文本属性。该脚本绑定到 Google 文档文件。例如,在运行脚本后,该点之后写入的任何内容的文本字体都会发生变化,而之前写入的文本保持不变。这是为了模仿 Google 文档中内置样式或字体菜单的行为方式。

这是我到目前为止的想法。它似乎在文档中全局更改文本字体,而不是仅将更改应用于运行代码后编写的文本。有什么建议么?

var cursor = DocumentApp.getActiveDocument().getCursor();

if(cursor){ 
var element4 = cursor.getElement()
var body = DocumentApp.getActiveDocument().getBody()
if (element4.editAsText) {
   body.editAsText().setFontFamily(DocumentApp.FontFamily.CALIBRI);
}
}

【问题讨论】:

  • 您没有回复这篇文章是有原因的吗?你试过下面的代码吗?

标签: google-apps-script google-docs


【解决方案1】:

下面的代码更改了您在其中选择文本的段落的FontFamily...它为后面的所有内容保持相同的样式并保留之前的所有内容。

如果您想更深入地了解精确度,您将不得不使用偏移量并在段落内的文本级别工作,但我认为这个版本就足够了。

function setStyle() {
var selection = DocumentApp.getActiveDocument().getSelection();
  if (!selection) {
    DocumentApp.getUi().alert('Cannot find a selection in the document.');
    return;
  }
  var selectedElements = selection.getSelectedElements();
  var element = selectedElements[0].getElement().getParent(); 
  element.setFontFamily(DocumentApp.FontFamily.CONSOLAS);
}

【讨论】:

    【解决方案2】:

    DocumentApp.FontFamily 枚举现已弃用。您应该改用字符串名称,例如“Consolas”(区分大小写!)。

    【讨论】:

      【解决方案3】:

      您可以访问 here 找到的 DocumentApp 参考的 setAttributes 部分

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-06
        相关资源
        最近更新 更多