首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何检索默认样式段落的字体系列和大小?

如何检索默认样式段落的字体系列和大小?
EN

Stack Overflow用户
提问于 2017-05-13 14:53:23
回答 2查看 387关注 0票数 1

我正在尝试编写一个函数,该函数将删除标题,但保留当前段落的字体和大小。

但是,字体系列/大小的值似乎不能从应用的标题设置的默认字体的段落中检索。

代码语言:javascript
复制
var cursor = DocumentApp.getActiveDocument().getCursor();  if (!cursor) return;
var ctext = cursor.getSurroundingText();
var para = ctext.asParagraph();
para.setHeading(DocumentApp.ParagraphHeading.HEADING1); // sets Arial 20
var text = ctext.asText();
var ff = text.getFontFamily();
var fs = text.getFontSize();
DocumentApp.getUi().alert(ff+" "+fs); // NULL NULL

我尝试访问标题的字体和大小,以此方式获取它们,但Google App Script似乎没有公开这些内容。

EN

回答 2

Stack Overflow用户

发布于 2018-06-10 06:50:06

可以使用Body.getHeadingAttributes(paragraphHeading)检索标头的样式属性。

段落的样式属性可以在字符级别被覆盖。这就是text.getFontFamily()text.getFontSize()正在检索的内容。但是,由于这些属性在您的示例中没有在字符级别被覆盖,因此它们返回为null,在这种情况下,必须返回到段落标题的样式定义。

我在您的示例中添加了回退逻辑:

代码语言:javascript
复制
var cursor = DocumentApp.getActiveDocument().getCursor();  if (!cursor) return;
var ctext = cursor.getSurroundingText();
var para = ctext.asParagraph();
para.setHeading(DocumentApp.ParagraphHeading.HEADING1); // sets Arial 20
var text = ctext.asText();
// Get heading attributes
var body = DocumentApp.getActiveDocument().getBody();
var headingAtts = body.getHeadingAttributes(para.getHeading());
var ff = text.getFontFamily();
//  If not set, fall back to heading attributes
if (ff == null) ff = headingAtts[DocumentApp.Attribute.FONT_FAMILY];
var fs = text.getFontSize();
//  If not set, fall back to heading attributes
if (fs == null) fs = headingAtts[DocumentApp.Attribute.FONT_SIZE];
DocumentApp.getUi().alert(ff+" "+fs); // Arial 20
票数 1
EN

Stack Overflow用户

发布于 2017-05-14 09:58:11

更重要的是,现在还不能做到这一点,我查看了Attributes对象,甚至直接访问它们也得到了相同的结果。作为一种解决办法,由于您知道默认值,因此可以将它们存储为对象,并在脚本中满足条件时对其进行设置:

代码语言:javascript
复制
function resetHeadings() {
  var body = DocumentApp.getActiveDocument().getBody();

  // store an object with default object attributes you can apply later
  var defaults = {
    "Heading 1": {
      FONT_SIZE: 20,
      FONT_FAMILY: 'Arial',
    },
    "Heading 2": {
      FONT_SIZE: 16,
      FONT_FAMILY: 'Arial'
    }
  };

  var pars = body.getParagraphs();

  for(var i in pars) {
    var props = pars[i].getAttributes();
    if(props["HEADING"] == "Heading 1") {

      // reset the Heading to normal
      props[i].setHeading(DocumentApp.ParagraphHeading.NORMAL);

      // Then, spoof with your stored defaults
      // You can chain .setAttributes() with the line above. Shown separate for clarity.
      props[i].setAttributes(defaults["Heading 1"]);
    }
  }
}

它不是完美的,但它会得到你所描述的结果。您可以对每个标题使用case/switch测试,而不是多个if语句。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43950155

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档