如何在保留编号的同时将ListItems从一个Google文档复制到另一个文档?

时间:2016-03-21 03:34:33

标签: google-apps-script google-docs

How to copy content and formatting between Google Docs?的已接受答案表明我们必须添加条件代码才能复制元素。但我不能让它适用于ListItem类型,因为目标文档显示没有原始编号的列表项。

var source_doc = DocumentApp.getActiveDocument();
var selection = source_doc.getSelection();
if (!selection) {
    var ui = DocumentApp.getUi();
    ui.alert('Please make a selection first.');
    return;
}

var target_doc = DocumentApp.create('CopyOf'+DocumentApp.getActiveDocument().getName());
var target_body = target_doc.getBody();

var elements = selection.getRangeElements();
for (var i = 1; i < elements.length; i++) {
    var source_element = elements[i].getElement();
    var copy_element = source_element.copy();
    if (copy_element.getType() == DocumentApp.ElementType.PARAGRAPH) {
        target_body.appendParagraph(copy_element);
    } else if (copy_element.getType() == DocumentApp.ElementType.LIST_ITEM) {
        // This does not keep the numbering on the list item. Why?
        target_body.appendListItem(copy_element);

        // And playing games with setListId doesn't work either:
        // copy_element.setListId(source_element);
        // target_body.appendListItem(copy_element);
    }
    // TODO: Handle the other elements here.
}

源文档显示如下:

source document

目标文档呈现如下:

bad rendering

如何保留ListItem格式?

这看起来要比应该的要困难得多:我真正想要的是将用户选择逐字复制到保留所有格式的新文档中,并从谷歌脚本中复制。

这似乎可以在更高的层次上完成。我可以手动复制和粘贴并保留格式,而不是从脚本中删除。

2 个答案:

答案 0 :(得分:1)

我猜这是导致使用Selection时出现问题的原因。直接从文档中读取似乎工作正常。

尝试将ListItem作为文本附加为解决方法。

target_body.appendListItem(copy_element.getText());

这只会复制文本,而不是格式化。您也可以尝试通过创建新列表来实现它,而不是直接复制元素。以下是可能有用的示例SO

答案 1 :(得分:0)

我遇到了类似的问题(但没有使用选择)。它被复制为列表,但没有任何实际的子弹。我只是手动重新设置子弹:

target_body.appendListItem(copy_element).setGlyphType(DocumentApp.GlyphType.NUMBER)
相关问题