在documentation sample之后,我正在尝试创建一个搜索google文档中的数字列表的函数,如果找到它,则会向列表中添加一个新项。我的代码运行良好(感谢@Serge insas以前的帮助)字符串,但没有段落对象。我知道我可以获得段落文本并将其添加到listItem,但后来我失去了格式化。有没有办法插入一个保留所有格式的段落? (我知道我可以使用var newElement = child.getParent().insertListItem(childIndex, elementContent.getText())
插入文本,而不会形成文字)
这里是代码:
function test() {
var targetDocId = "1A02VhxOWLUIdl8LTV1tt2S1yASDbOq77VbsUpxPa6vk";
var targetDoc = DocumentApp.openById(targetDocId);
var body = targetDoc.getBody();
var elementContent = targetDoc.getChild(2); // a paragraph with its formating
var childIndex = 0;
for (var p= 0; p< targetDoc.getNumChildren(); p++) {
var child = targetDoc.getChild(p);
if (child.getType() == DocumentApp.ElementType.LIST_ITEM){
while(child.getType() == DocumentApp.ElementType.LIST_ITEM){
child = targetDoc.getChild(p)
Logger.log("child = " + child.getText())
childIndex = body.getChildIndex(child);
Logger.log(childIndex)
p++
}
child = targetDoc.getChild(p-2);
var listId = child.getListId();
if (child.getText() == '') {
childIndex = childIndex -1;
}
Logger.log(childIndex)
var newElement = child.getParent().insertListItem(childIndex, elementContent);
newElement.setListId(child);
var lastEmptyItem = targetDoc.getChild(childIndex +1).removeFromParent();
break;
}
这里是我的targetDoc的屏幕截图(注意第二项,Paragraph
):
答案 0 :(得分:0)
我知道这个问题已经过时了,但是我已经提出了一个解决方案,并会留给那些可能需要它的人。它还不完整,因为我还没有找到一种方法将任何内联图形和方程复制到一个新元素......
无论如何,这是我的代码,如果你想要转换为列表项的段落只有文本和内联图像,它将很好用。
function parToList() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
//gets the paragraph at index 1 on body -> can be changed to what you want
var par = body.getChild(1);
var childs = [];
for (var i = 0; i<par.getNumChildren(); i++) {
var child = par.getChild(0);
childs.push(child);
child.removeFromParent();
};
par.removeFromParent();
//puts the list item on index 1 of body -> can be changed to the wanted position
var li = body.insertListItem(1, "");
childs.reverse();
for (var j in childs) {
var liChild = childs[j];
var childType = liChild.getType();
if (childType == DocumentApp.ElementType.EQUATION) {
//still need to find a way to append an equation
} else if (childType == DocumentApp.ElementType.INLINE_DRAWING) {
//still need to find a way to append an inlineDrawing
} else if (childType == DocumentApp.ElementType.INLINE_IMAGE) {
li.appendInlineImage(liChild);
} else if (childType == DocumentApp.ElementType.TEXT) {
li.appendText(liChild);
};
};
};
干杯