我正在尝试编写一个函数,该函数将删除标题,但保留当前段落的字体和大小。
但是,字体系列/大小的值似乎不能从应用的标题设置的默认字体的段落中检索。
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似乎没有公开这些内容。
发布于 2018-06-10 06:50:06
可以使用Body.getHeadingAttributes(paragraphHeading)
检索标头的样式属性。
段落的样式属性可以在字符级别被覆盖。这就是text.getFontFamily()
和text.getFontSize()
正在检索的内容。但是,由于这些属性在您的示例中没有在字符级别被覆盖,因此它们返回为null
,在这种情况下,必须返回到段落标题的样式定义。
我在您的示例中添加了回退逻辑:
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
发布于 2017-05-14 09:58:11
更重要的是,现在还不能做到这一点,我查看了Attributes对象,甚至直接访问它们也得到了相同的结果。作为一种解决办法,由于您知道默认值,因此可以将它们存储为对象,并在脚本中满足条件时对其进行设置:
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语句。
https://stackoverflow.com/questions/43950155
复制相似问题