Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy content and formatting between Google Docs?

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?

like image 341
craftApprentice Avatar asked Nov 14 '13 19:11

craftApprentice


1 Answers

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();
}
like image 172
Serge insas Avatar answered Sep 22 '22 10:09

Serge insas