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

前端 未结 4 777
别那么骄傲
别那么骄傲 2021-02-01 21:35

I feel like a total noob posting here. I know CSS, HTML, and XML pretty well but have always avoided JS. I know very little javascript and recently started a Lynda.com course

相关标签:
4条回答
  • 2021-02-01 22:03

    Here is the code to do it properly (works in 2019,2020,2021):

    /**
     * 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();
    }
    
    0 讨论(0)
  • 2021-02-01 22:06

    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.

      Access rights

    2. Grab the fileId from the URL -

      enter image description here

    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.

      deploy settings

    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.

    0 讨论(0)
  • 2021-02-01 22:06

    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

    0 讨论(0)
  • 2021-02-01 22:12

    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.

    0 讨论(0)
提交回复
热议问题