2016-11-22 29 views
0

我在嘗試將作爲模板的活動文檔的頁眉/頁腳複製到新創建的文檔中。我能夠很容易地獲得文本,但我無法獲得格式,字體或水平對齊。複製Google文檔標題使用GAS格式化

我的理論是,我可以做類似

newDocHeader.setAttributes(activeDocHeader.getAttributes()); 

但是,我仍然只能看到所左對齊純文本。當檢查表頭的attributes對象我得到如下:

({ 
    FONT_SIZE:null, 
    ITALIC:null, 
    STRIKETHROUGH:null, 
    FOREGROUND_COLOR:null, 
    BOLD:null, 
    LINK_URL:null, 
    UNDERLINE:null, 
    FONT_FAMILY:null, 
    BACKGROUND_COLOR:null 
}) 

我通過標題的子對象試圖循環和每個孩子執行類似setAttributes(getAttributes),但無濟於事。

我還以爲頁眉/頁腳對象的copy()功能將是有前途的,但是當我試圖

newDocFooter = activeDocFooter.copy(); 

但是,這會產生沒有文字或格式空白頁腳。

有沒有一種很好的方法將格式,字體和水平對齊從一個頁眉/頁腳複製到另一個頁面?

回答

0

我與DocumentApp完全陌生,但這個廣泛爲我工作:廣泛只有

/** 
* Copies headers from one document to another. 
* @param {string} source The source document URL. 
* @param {string} target The target document URL. 
*/ 
function copyHeader(source, target) {  
    // Used to map from child types to required "append<X>" method 
    var functionMap = { 
    PARAGRAPH: 'appendParagraph', 
    LIST_ITEM: 'appendListItem', 
    HORIZONTAL_RULE: 'appendHorizontalRule', 
    IMAGE: 'appendImage', 
    TABLE: 'appendTable' 
    }; 

    var t = DocumentApp.openByUrl(target); 
    var s = DocumentApp.openByUrl(source); 

    var sourceHeader = s.getHeader(); 
    var targetHeader = t.getHeader(); 

    // If there is no header in the target doc, add one 
    if (!targetHeader) { 
    targetHeader = t.addHeader(); 
    } 
    targetHeader.clear(); 

    // Docs requires one child element, so one will remain even 
    // after clearing. Get a reference to it so it can be removed 
    var targetNumChild = targetHeader.getNumChildren(); 
    if (targetNumChild === 1) { 
    var placeholderElement = targetHeader.getChild(0); 
    } 

    // Copy across each element to the target doc 
    var c = sourceHeader.getNumChildren(); 
    for (var i = 0; i < c; i++) { 
    var element = sourceHeader.getChild(i).copy(); 
    var method = functionMap[element.getType()]; 
    targetHeader[method](element); 
    } 

    // Remove the saved element if required 
    if (targetHeader.getNumChildren() > 1 && placeholderElement) { 
    targetHeader.removeChild(placeholderElement); 
    } 
} 

我說,因爲格式,如粗體,水平居中,水平規則等全部複製跨罰款,但奇怪的是,名單似乎從編號變成了名詞,因此翻譯中丟失了一些東西。

它可能需要一點調整,當然有一個更簡單的方法,但是如果沒有其他任何東西,這可能是一個開始。

源文件:

enter image description here

目標文件,注意,列表類型是不完全正確!:

enter image description here

希望它能幫助。