Pages

Wednesday, 26 December 2018

Copy a Doc and add paragraphs

The following Google Apps Script code is designed to make a copy of an existing Google Doc and then make changes to the content of the new file. This was initially developed to feed into an Exceptional Circumstances system that will be detailed in a later blog post, where a document is created for each student that fills in a form request.

The script starts by getting the ID of the file to copy ('getFileById'), then the destination folder ID of where the new file will be copied ('getFolderById'). A copy is then made using these parameters, along with a new file name of new doc (this can be altered as required). During the copy it grabs the file Url ('getUrl') so that 'DocumentApp' can then open it and get the body to then change a tag for <<Name>> and loop through adding 5 paragraph lines.

function copyDoc_Paragraphs() {
// document ID of the file to be copied
var docId = 'insert your file ID';
// instruct DriveApp to get this document
var templateDoc = DriveApp.getFileById(docId);
// folder ID of where the copied file is to be saved
var folderId = 'insert your folder ID';
// instruct DriveApp to get this folder
var destinationFolder = DriveApp.getFolderById(folderId);
// copy the file to the destination and get the Url
var newDocUrl = templateDoc.makeCopy('new doc', destinationFolder).getUrl();
// open the file by the Url
var newDoc = DocumentApp.openByUrl(newDocUrl);
// get the body of the document
var docBody = newDoc.getBody();
// replace the tag with 'Eric'
docBody.replaceText('<<Name>>', 'Eric');
// add 5 paragraph lines
for (var i=1; i<6; i++) {
docBody.appendParagraph('this is paragraph ' + i);
}
}
Copy a Doc and add paragraphs.gs

No comments:

Post a Comment