2013-12-22 58 views
1

documentation sample之後,我試圖創建一個函數,在google文檔中搜索一個已編號的列表,如果它找到它,就向列表中添加一個新項目。我的代碼運行良好(感謝@Serge insas以前的幫助)字符串,但不適用於段落對象。我知道我可以得到段落文本並將其添加到listItem中,但是然後我失去了格式化。有沒有辦法插入一段保留所有格式的段落? (我知道我可以使用var newElement = child.getParent().insertListItem(childIndex, elementContent.getText())不要插入文本無話在格式化)如何在listItem中插入段落對象,以保存段落每個單詞的格式化?

下面的代碼:

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):

enter image description here

回答

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); 
    }; 
    }; 
}; 

乾杯