Script to automatically make a copy of a Google Document for editing

不羁的心 提交于 2019-12-02 19:26:54
Arun Nagarajan

You can certainly do this with Apps Script. Only takes a couple of lines. In fact, you can use just the version I wrote below.

Here is how I would do it -

  1. Ensure you original document is at least read enabled for the folks that will be accessing it.

  2. Grab the fileId from the URL -

  3. Write a web app in Apps Script with the following code -

    function doGet(e) {
      //file has to be at least readable by the person running the script
      var fileId = e.parameters.fileId;  
      if(!fileId){
        //have a default fileId for testing. 
        fileId = '1K7OA1lnzphJRuJ7ZjCfLu83MSwOXoEKWY6BuqYitTQQ'; 
      }
      var newUrl = DocsList.getFileById(fileId).makeCopy('File copied to my drive').getUrl(); 
      return HtmlService.createHtmlOutput('<h1><a href="'+newUrl+'">Open Document</a></h1>');
    }
    
  4. Deploy it to run as the person accessing the app.

One key thing to remember is that a web app built by Apps Script cannot force open a new window automatically. Instead we can show a link which is clickable into the document in edit mode.

You can see it in action here (will create some dummy file) -

https://script.google.com/macros/s/AKfycbyvxkYqgPQEb3ICieywqWrQ2-2KWb-V0MghR2xayQyExFgVT2h3/exec?fileId=0AkJNj_IM2wiPdGhsNEJzZ2RtZU9NaHc4QXdvbHhSM0E

You can test this by putting in your own fileId.

Riyafa Abdul Hameed

Since DocsList is deprecated, currently you can make a copy of a file using the following code:

File file=DriveApp.getFileById(fileId).makeCopy(fileName, folder);

where fileId can be obtained as explained in the answer by Arun Nagarajan.

Update as of 2015, Google Script removed the fileId for reasons unknown. The previous method of appending "/copy" to the URL of the Google doc has been re-enabled. Ex) https://docs.google.com/document/d/1GTGuLqahAKS3ptjrfLSYCjKz4FBecv4dITPuKfdnrmY/copy

Here is the code to do it properly (as of year 2019):

/**
 * Create custom menu when document is opened.
 */
function onOpen() {
  DocumentApp.getUi()
    .createMenu('For Students')
    .addItem('Make a copy', 'makeACopy')
    .addToUi();
}

function makeACopy() {
  var templateId = DocumentApp.getActiveDocument().getId();
  DriveApp.getFileById(templateId).makeCopy();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!