How to copy one or more existing pages of a document using google apps script

30,355

Following your comment, here is the full code I use to merge an undetermined number of docs in a new one. All document IDs are in an array of IDs as argument for the main function, the results is a new doc with "multi-page" appended to the name. If you need more explanation than provided by the in code comments just let me know... (note that it will work only for documents containing text and tables, if you have images ot other data type you'll have to handle that case in the main loop where we check the ElementType following the same logic)


EDIT : first code removed, following your update I tried this approach assuming you have only paragraphs in your master doc... give it a try and I guess you could start from there to developp your project.

function Serialletter_Singledocument() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Datenbank");
  var LastColumn = sheet.getLastColumn();

  //here you need to get document id from url (Example, 1oWyVMa-8fzQ4leCrn2kIk70GT5O9pqsXsT88ZjYE_z8)
  var FileTemplateFileId = "1Wrf2qvUTyc5tMmJIly40Z4U4sJb4-QhT5z-UfJmtQ-M" //Browser.inputBox("ID der Serienbriefvorlage (aus Dokumentenlink kopieren):");
  var doc = DocumentApp.openById(FileTemplateFileId);
  var DocName = doc.getName();

  var headpara=' ***** ';

  // Fetch entire table containing data
  var data = sheet.getDataRange().getValues();

  //Create copy of the template document and open it
  var SerialLetterID = DocsList.getFileById(FileTemplateFileId).makeCopy(DocName +" Serienbrief").getId();
  var docCopy = DocumentApp.openById(SerialLetterID);
  var totalParagraphs = docCopy.getBody().getParagraphs() ;// get the total number of paragraphs elements
  Logger.log(totalParagraphs);
  var elements = [];
  for ( var i = 1; i < data.length; i++) { //do for every record in the spreadsheet (containing the content to replace the variables in the letter)
    for (var e=0;e<totalParagraphs.length;e++){

      var element = totalParagraphs[e].copy();
//      Logger.log(element.editAsText().getText())
      for(var c=0;c<data[0].length;c++){     
        element.replaceText("<" +data[0][c] +">", data[i][c]); //replace variable (from column title) with actual value
      }
      elements.push(element);// store paragraphs in an array
    }

    for(var el=0;el<elements.length;el++){ 
      var paragraph = elements[el].copy();
      docCopy.getBody().appendParagraph(paragraph);
    }
  docCopy.getBody().appendPageBreak()
  }
  docCopy.saveAndClose();

  Browser.msgBox("Serienbrief ist erstellt. Sie finden die erstellten Dokumente in Google Drive unter Meine Ablage");
}
Share:
30,355
Heinz Ruffieux
Author by

Heinz Ruffieux

Updated on January 13, 2020

Comments

  • Heinz Ruffieux
    Heinz Ruffieux over 4 years

    I have sucessfully written a small script, which creates a serial letter (physical letter to several recipients) based on data in a Google spreadsheet creating a new document for each letter/addresse. It works, but for large mailings this approach is a bit cumbersome as a large amount of documents are created and need to be printed individually.

    Now i would like to do the same but as a result having all of the letters in one single Google document.

    Is there any way to copy the content of an existing document and inserting it a number of times into the same or any other documents (i.e. copy/paste via apps script)?