Autofill Google Docs in 1-Click with 100% Free Apps Script Code

AppSScript Code

function onOpen() {
  const ui = SpreadsheetApp.getUi();
  ui.createMenu("OutrightStore")
    .addItem('Show Sidebar', 'showSidebar')
    .addToUi();
  // Call your function here if you want it to run automatically on open
  showSidebar();
}
// Function to create and display a custom sidebar
function showSidebar() {
  var html = HtmlService.createHtmlOutputFromFile('Sidebar4')
      .setTitle('Sidebar Form')
      .setWidth(300);
  SpreadsheetApp.getUi().showSidebar(html);
}


function createHeadersFromForm(headers) {
  // Get the active sheet in the spreadsheet
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
 
  // Split the headers string by comma to get individual headers
  const headerArray = headers.split(",");
 
  // Set the headers in the first row dynamically
  sheet.getRange(1, 1, 1, headerArray.length).setValues([headerArray]);
 
  // Apply formatting to the header row
  const headerRange = sheet.getRange(1, 1, 1, headerArray.length);
  headerRange.setFontWeight("bold"); // Set text to bold
  headerRange.setFontSize(14); // Set font size to 14
}


function createDocumentsFromSheet(templateFileId) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Sheet1"); // Replace "Sheet1" with the name of your sheet
  var dataRange = sheet.getDataRange();
  var dataValues = dataRange.getValues();
 
  // Get the placeholders from the first row of the sheet
  var placeholders = dataValues[0];


  // Get the template document
  var templateDoc = DriveApp.getFileById(templateFileId);
  var templateName = templateDoc.getName(); // Get the name of the template document


  // Create a folder to store the generated documents
  var folder = DriveApp.createFolder("Generated Documents");


  // Loop through the rows in the sheet starting from the second row (index 1) to skip the header row
  for (var i = 1; i < dataValues.length; i++) {
    var row = dataValues[i];


    // Replace the placeholders in the template with the row data
    var templateCopy = templateDoc.makeCopy();
    var doc = DocumentApp.openById(templateCopy.getId());
    var body = doc.getBody();


    for (var j = 0; j < placeholders.length; j++) {
      var placeholder = "{{" + placeholders[j] + "}}"; // Assuming placeholders are in the first row
      var value = row[j]; // Get the corresponding value from the row


      if (typeof value === 'object' && value instanceof Date) {
        // Format the date value
        value = value.toLocaleDateString();
      }


      body.replaceText(placeholder, value);
    }


    // Save and close the document
    doc.saveAndClose();


    // Set the name of the copied document to match the template name
    var copiedFile = DriveApp.getFileById(templateCopy.getId());
    copiedFile.setName(templateName);


    // Move the document to the generated documents folder
    var newFile = folder.createFile(copiedFile);


    // Get the email address from the row
    var email = row[2]; // Assuming Email is in column C (index 2)


    // Send the PDF file via email
    if (email) {
      var subject = "Generated Document from " + templateName; // Include the template name in the subject
      var mailBody = "Please find the generated document attached.";
      MailApp.sendEmail(email, subject, mailBody, { attachments: [newFile.getAs(MimeType.PDF)] });
    }


    // Delete the template copy
    copiedFile.setTrashed(true);
  }


  // Provide a link to the generated documents folder
  var folderUrl = folder.getUrl();
  Logger.log("Generated documents: " + folderUrl);
}

HTML Code

<!DOCTYPE html>
<html>
<head>
  <base target="_top">
  <style>
    body {
      font-family: Arial, sans-serif;
      background-color: #f4f4f4;
      margin: 0;
      padding: 0;
    }
    .container {
      max-width: 500px;
      height: 500px;
      margin: 0px auto;
      padding: 20px;
      background-color: #fff;
      border-radius: 5px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    }
    h2 {
      text-align: center;
      color: #333;
    }
    label {
      font-weight: bold;
    }
    select,
    input[type="text"],
    input[type="button"],
    input[type="email"] {
      width: 100%;
      padding: 10px;
      margin: 5px 0 15px 0;
      border: 1px solid #ccc;
      border-radius: 3px;
      box-sizing: border-box;
      font-size: 16px;
    }
    input[type="button"] {
      background-color: #4CAF50;
      color: white;
      border: none;
      cursor: pointer;
    }
    input[type="button"]:hover {
      background-color: #45a049;
    }
  </style>
</head>
<body>
  <div class="container">
    <h2>Document Credentials</h2>
    <form id="documentForm">
      <label for="documentID">Template Document ID:</label><br>
      <input type="text" id="documentID" name="documentID" placeholder="Enter Document ID"><br><br>

      <label for="headers">Headers (comma-separated):</label><br>
      <input type="text" id="headers" name="headers" placeholder="Enter Headers"><br><br>

      <input type="button" value="Create Headers" onclick="createHeaders()">
      <input type="button" value="Submit" onclick="submitRequest()">
    </form>
  </div>

  <script>
    function createHeaders() {
      // Get the headers from the input field
      var headers = document.getElementById("headers").value;
     
      // Call the createHeadersFromForm function with the headers
      google.script.run.createHeadersFromForm(headers);
    }
   
    function submitRequest() {
      // Get the templateFileId from the input field
      var templateFileId = document.getElementById("documentID").value;
     
      // Call the createDocumentsFromSheet function with the templateFileId
      google.script.run.createDocumentsFromSheet(templateFileId);
    }
  </script>
</body>
</html>