如何在Google文档之间复制内容和格式? [英] How to copy content and formatting between Google Docs?
问题描述
我需要复制Google文档的内容,并将其附加到其他文档。如果我使用类似这样的内容:
newDoc.getBody()。appendParagraph(template.getText());
p> ...我得到了文本,但失去了原始文件中的格式。 (粗体,斜体等)。
如何将内容和格式复制到新文档?是否有可能将所有内容都分配给一个变量,并将其复制/粘贴到新文档中?
,你必须迭代文档中的所有元素,并逐一复制它们。
同一主题上有多个线程,请尝试下面这个例子: 如何使用谷歌应用程序脚本复制文档的一个或多个现有页面
仔细阅读代码并添加您所有的内容类型应该在你的文档(表格,图像,分页...)中见面。编辑:这是一个关于这个想法的试验(开始)
函数copyDoc(){
var sourceDoc = DocumentApp.getActiveDocument()。getBody();
var targetDoc = DocumentApp.create('CopyOf'+ DocumentApp.getActiveDocument()。getName());
// var targetDoc = DocumentApp.openById('another doc ID');
var totalElements = sourceDoc.getNumChildren(); $ j
$ b for(var j = 0; j var body = targetDoc.getBody()
var element = sourceDoc.getChild(j) 。复制();
var type = element.getType();
if(type == DocumentApp.ElementType.PARAGRAPH){
body.appendParagraph(element);
}
else if(type == DocumentApp.ElementType.TABLE){
body.appendTable(element);
}
else if(type == DocumentApp.ElementType.LIST_ITEM){
body.appendListItem(element);
}
// ...添加其他条件(页眉,页脚...
)
targetDoc.saveAndClose();
}
code>
I need to copy the content of a Google Document, and append it to another Document. If I use something like this:
newDoc.getBody().appendParagraph(template.getText());
...I get the text, but lose the formatting that was in my original file. (Bold, Italic, etc.)
How can I copy the contents and formatting to the new document? Is it possible to assign everything to one variable, and copy / paste it to the new document?
Not using only 1 variable , you'll have to iterate all the elements in the doc and copy them one by one.
there are multiple threads on the same subject, try for example this one : How to copy one or more existing pages of a document using google apps script
just read carefully the code and add all the content types that you are supposed to meet in your document (tables, images, pagebreaks...)
EDIT : here is a trial on that idea (to start with)
function copyDoc() {
var sourceDoc = DocumentApp.getActiveDocument().getBody();
var targetDoc = DocumentApp.create('CopyOf'+DocumentApp.getActiveDocument().getName());
// var targetDoc = DocumentApp.openById('another doc ID');
var totalElements = sourceDoc.getNumChildren();
for( var j = 0; j < totalElements; ++j ) {
var body = targetDoc.getBody()
var element = sourceDoc.getChild(j).copy();
var type = element.getType();
if( type == DocumentApp.ElementType.PARAGRAPH ){
body.appendParagraph(element);
}
else if( type == DocumentApp.ElementType.TABLE){
body.appendTable(element);
}
else if( type == DocumentApp.ElementType.LIST_ITEM){
body.appendListItem(element);
}
// ...add other conditions (headers, footers...
}
targetDoc.saveAndClose();
}
这篇关于如何在Google文档之间复制内容和格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!