我如何使用 google 应用程序脚本获取 google 文档中的所有 h1 标题?
How do i get all h1 headings in google doc with google apps script?
基本上,我想获取活动文档中的所有 h1 标题并将其更改为 h2,还打算做一些字体样式等
function abc() {
var body = DocumentApp.getActiveDocument().getBody();
// instead of appending the paragraph in line 8 i want to get all the h1 heading that are avialble in the active document
var par1 = body.appendParagraph("changing h1 to h2 heading");
par1.setHeading(DocumentApp.ParagraphHeading.HEADING2);
}
可以参考这个示例代码:
function findHeader() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
// Define the search parameters.
var searchType = DocumentApp.ElementType.PARAGRAPH;
var searchHeading = DocumentApp.ParagraphHeading.HEADING1;
var searchResult = null;
var style = {};
style[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
style[DocumentApp.Attribute.BOLD] = true;
// Search until the paragraph is found.
while (searchResult = body.findElement(searchType, searchResult)) {
var par = searchResult.getElement().asParagraph();
if (par.getHeading() == searchHeading) {
// Found one, update
par.setHeading(DocumentApp.ParagraphHeading.HEADING2);
par.setAttributes(style);
}
}
}
它有什么作用?
- 使用 Body.findElement(elementType, from)
在文档中搜索段落
- 使用Paragraph.getHeading()检查当前段落的标题
- 如果标题为
DocumentApp.ParagraphHeading.HEADING1
,请将标题设置为 DocumentApp.ParagraphHeading.HEADING2
并使用 Paragraph.setHeading(heading) and Paragraph.setAttributes(attributes) 更改其段落属性
输出:
之前:
之后:
基本上,我想获取活动文档中的所有 h1 标题并将其更改为 h2,还打算做一些字体样式等
function abc() {
var body = DocumentApp.getActiveDocument().getBody();
// instead of appending the paragraph in line 8 i want to get all the h1 heading that are avialble in the active document
var par1 = body.appendParagraph("changing h1 to h2 heading");
par1.setHeading(DocumentApp.ParagraphHeading.HEADING2);
}
可以参考这个示例代码:
function findHeader() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
// Define the search parameters.
var searchType = DocumentApp.ElementType.PARAGRAPH;
var searchHeading = DocumentApp.ParagraphHeading.HEADING1;
var searchResult = null;
var style = {};
style[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
style[DocumentApp.Attribute.BOLD] = true;
// Search until the paragraph is found.
while (searchResult = body.findElement(searchType, searchResult)) {
var par = searchResult.getElement().asParagraph();
if (par.getHeading() == searchHeading) {
// Found one, update
par.setHeading(DocumentApp.ParagraphHeading.HEADING2);
par.setAttributes(style);
}
}
}
它有什么作用?
- 使用 Body.findElement(elementType, from) 在文档中搜索段落
- 使用Paragraph.getHeading()检查当前段落的标题
- 如果标题为
DocumentApp.ParagraphHeading.HEADING1
,请将标题设置为DocumentApp.ParagraphHeading.HEADING2
并使用 Paragraph.setHeading(heading) and Paragraph.setAttributes(attributes) 更改其段落属性
输出:
之前:
之后: