签名板(画布)到 Google 表格

问题描述 投票:0回答:1

我正在尝试创建一个自动填充到 Google 表格中的表单。目前,我可以使用 自动将基本文本字段填充到 Google Sheets 中,但我现在需要尝试让用户编写数字签名并将其也放入 Google Sheets 中 - 大概是通过使用 toDataURL 和然后将其发送到 Google 表格?

但是...我对此类事情的经验很少,并且完全不知道如何实现这一点!

到目前为止,我已经从各种来源和视频中获取了代码来达到我现在所处的阶段,但现在它变得混乱了。

页面上的一些内容有些敏感,所以我会在这里发布我能找到的任何代码。

这是当前使用的一些 HTML - 抱歉,有点乱! (其中一些可能根本没有用,我一直在搞乱它,以至于我在这一点上迷失了!)

    <h4>Billing Address</h4>
        <input type="text" name="address-number" placeholder="House/Apartment Number">
            <input type="text" name="address-street" placeholder="Street Name">
        <input type="text" name="address-town" placeholder="Town/City">
        <input type="text" name="address-county" placeholder="County">
            <input type="text" name="address-postcode" placeholder="Postcode">
                    
                    
    <div class="flex-row">
                <div class="wrapper">
                     <canvas id="signature-pad" width="400" height="200"></canvas>
                </div>
                <div>
                     <input type="hidden" name="signature-pad" />
                </div>
                     <div class="clear-btn">
                     <button id="clear"><span> Clear </span></button>
                </div>
                </div> 
                
                 <div>
                
<script src="https://cdnjs.cloudflare.com/ajax/libs/signature_pad/1.3.5/signature_pad.min.js" integrity="sha512-kw/nRM/BMR2XGArXnOoxKOO5VBHLdITAW00aG8qK4zBzcLVZ4nzg7/oYCaoiwc8U9zrnsO9UHqpyljJ8+iqYiQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

   <input type="submit" value="Submit" id="submit">
</div>
</form>

这是当前正在使用的 Javascript - 它更加混乱,而且我确信其中很多都没有做任何事情。再次道歉。

const form = document.forms['contact-form']


form.addEventListener('submit', e => {
  e.preventDefault()
  fetch(scriptURL, { method: 'POST', body: new FormData(form)})
  .then(response => alert("Thank you! your form is submitted successfully." ))
  .then(() => { window.location.reload(); })
  .catch(error => console.error('Error!', error.message))
})

 
var canvas = document.getElementById("signature-pad");


       function resizeCanvas() {
           var ratio = Math.max(window.devicePixelRatio || 1, 1);
           canvas.width = canvas.offsetWidth * ratio;
           canvas.height = canvas.offsetHeight * ratio;
           canvas.getContext("2d").scale(ratio, ratio);
       }
       
       window.onresize = resizeCanvas;
       resizeCanvas();

       var signaturePad = new SignaturePad(canvas, {
        backgroundColor: 'rgb(250,250,250)'
       });

       document.getElementById("clear").addEventListener('click', function(){
        signaturePad.clear();
       });
       
       
function onSubmit(e) {
    console.log({
        'signature-pad' : dataURL,
    });
}

这一切都通过某种脚本连接到 Google Sheets - 老实说,我根本不知道它是如何工作的。这对我来说有点黑魔法。如果我需要提供更多代码或信息,请告诉我。

从根本上来说,我希望能够让签名板以某种方式输出签名图像,然后在用户提交时自动填充到 Google 表格中。

非常感谢您对此提供的任何帮助,以及任何能够破译我陷入疯狂的人。非常感谢!

我尝试了许多不同的代码变体,其中大部分已经丢失。抱歉。大多数时候,我半期望它能起作用(几乎没有信心),但它根本不起作用。 Google 表格将像往常一样自动填充,但不会填充任何签名部分。我尝试更改 onSubmit 部分以生成 URL,但我认为我做得不正确。我尝试过在代码开头添加其他“var”段,例如以下示例:使用 php 创建带有数字/电子签名的 HTML 表单 - 但我发现那些“var”一开始似乎破坏了 WordPress 中的签名板,它甚至不允许用户在框中绘图。一旦我删除它们,签名板就会再次工作。

我尝试使用我当前拥有的代码和链接的代码,但都不起作用。我目前拥有的可以让我正确使用该垫,但我无法弄清楚如何生成 URL 并将其发送到 Google Sheets,就像其他代码可能允许的那样。但是,链接的代码不允许用户使用签名板。我不确定为什么,我尝试将代码合并到不同的位置并从每个位置获取位,但没有成功,每次我失败都是因为它无法被绘制,或者不知道如何发送到 URL谷歌表格。

感谢您的帮助!

javascript html css google-sheets digital-signature
1个回答
0
投票

替代解决方案:使用 Google App 脚本获取签名

我创建了一个脚本,可以自动将包括签名在内的所有详细信息发送到 Google Sheet。请按照以下步骤进行操作。


步骤:

  1. 在您的
    Google Drive
    上创建一个文件夹,然后创建文件夹
    Anyone with the link
    并选择
    Viewer
  2. 创建一个
    Spreadsheet
    ,您将在其中存储数据并输入每个值的标题。
  3. 通过电子表格菜单栏上的
    AppScript
    打开
    Extensions
  4. 将此代码粘贴到
    Code.gs
function doGet() {
  // Creates and returns an HTML output from the 'form' file, setting the title of the window.
  return HtmlService.createHtmlOutputFromFile('form')
    .setTitle('Form with Signature');
}

function doPost(e) {
  // Extracts form data from the event object (e).
  const formData = e.parameter;

  // Open the Google Sheet
  const sheet = SpreadsheetApp.getActiveSpreadsheet(); // Gets the active spreadsheet.
  const sheetName = sheet.getSheetByName("Sheet1"); // Gets the specific sheet named "Sheet1".

  // Retrieve the signature from the form data
  const signature = formData.signature;

  let fileUrl = ''; // Variable to store the URL of the uploaded signature file.
  let blob = null;  // Variable to hold the blob of the image.
  let id = null;    // Variable to hold the ID of the uploaded file.

  if (signature) {
    // If there is a signature, process it
    // Remove the prefix "data:image/png;base64," to get the base64 string.
    const base64Image = signature.split(',')[1];

    // Convert the base64 string to a Blob object (binary large object).
    blob = Utilities.newBlob(Utilities.base64Decode(base64Image), 'image/png', 'signature.png');

    // Save the Blob to Google Drive in a specific folder (use your folder ID).
    const folder = DriveApp.getFolderById('REPLACE-WITH-YOUR-ACTUAL-FOLDER-ID'); // Replace with your folder ID.
    const file = folder.createFile(blob); // Creates the file in the folder.
    fileUrl = file.getUrl(); // Gets the URL of the newly created file.
    
    // Extract the file ID from the URL
    id = fileUrl.split("/");
    
    // Create an IMAGE formula for Google Sheets to display the uploaded image.
    formData.image = `=IMAGE("https://drive.google.com/thumbnail?sz=w1000&id=${id[5]}", 4, 50, 100)`; 
  }

  // Add the form data to the Google Sheet
  sheetName.appendRow([
    formData['address-number'],  // Adds address number from form data.
    formData['address-street'],  // Adds address street from form data.
    formData['address-town'],     // Adds address town from form data.
    formData['address-county'],   // Adds address county from form data.
    formData['address-postcode'],  // Adds address postcode from form data.
    formData.image                // Adds the image formula for the signature.
  ]);

  // Returns a success message as plain text.
  return ContentService.createTextOutput("Success");
}

注意: 在代码的第 31 行,确保粘贴您实际的

Folder ID

  1. 通过单击
    HTML
    符号创建
    +
    文件。

htmlfile

  1. 将此代码粘贴到新创建的
    HTML
    文件上:

<!DOCTYPE html>
<html>

<head>
  <base target="_top">
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">

  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
    integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous">
  </script>
  <style>
    #signature-pad {
      border: 1px solid #000;
      width: 400px;
      height: 200px;
    }

    .clear-btn {
      margin-top: 10px;
    }
  </style>
</head>

<body>
  <h4>Billing Address</h4>
  <form id="contact-form">
    <input type="text" name="address-number" placeholder="House/Apartment Number" required><br>
    <input type="text" name="address-street" placeholder="Street Name" required><br>
    <input type="text" name="address-town" placeholder="Town/City" required><br>
    <input type="text" name="address-county" placeholder="County" required><br>
    <input type="text" name="address-postcode" placeholder="Postcode" required><br>

    <h4>Signature</h4>
    <canvas id="signature-pad"></canvas>
    <input type="hidden" name="signature" id="signature">
    <div class="clear-btn">
      <button type="button" id="clear">Clear</button>
    </div>

    <br>
    <input type="submit" value="Submit">
  </form>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/signature_pad/1.3.5/signature_pad.min.js"></script>
  <script>
    // Signature Pad setup
      var canvas = document.getElementById("signature-pad");
      var signaturePad = new SignaturePad(canvas, {
        backgroundColor: 'rgb(250, 250, 250)'
      });

      // Clear the signature
      document.getElementById("clear").addEventListener('click', function() {
        signaturePad.clear();
      });

      // Submit form with signature
      var form = document.getElementById('contact-form');
      form.addEventListener('submit', function(e) {
        e.preventDefault();

        // Check if signature is empty
        if (signaturePad.isEmpty()) {
          alert("Please provide a signature first.");
          return;
        }

        // Convert signature to data URL
        var signatureDataURL = signaturePad.toDataURL();

        // Set the value of hidden input field with the signature data
        document.getElementById("signature").value = signatureDataURL;

        // Send form data to Apps Script
        fetch("https://script.google.com/macros/s/AKfycbz0MurKGjNAsWdgpi2ifjSfHj-gQQuBFpSlGVq0hg5xHn7lP_vZosUxzzMrGA4b3GfdtA/exec", { //Replace this with your actual Web App Link
          method: 'POST',
          body: new FormData(form)
        })
        .then(response => response.text())
        .then(result => {
          alert("Form submitted successfully!");
          form.reset();  // Reset the form after submission
          signaturePad.clear();  // Clear the signature pad
        })
        .catch(error => {
          console.error('Error:', error);
        });
      });
  </script>
</body>

</html>

  1. 单击屏幕右上角的
    Deploy
    部署您的 Web 应用程序。单击
    New Deployment
    选择
    Web App
    作为类型并填写必要的表格。请务必选择
    Anyone
    谁有权访问。

configuration

  1. 复制部署后将出现的 Web 应用程序的
    URL
    ,因为您将把它粘贴到
    HTML
    文件上,并且需要它来访问您的 Web 应用程序。

注意: 在代码的第 76 行,确保粘贴您实际的

Web App URL

示例输出:

网络应用程序:

webapp

电子表格

Spreadsheet

参考资料:

请注意,我不隶属于所提供的网站。我只是碰巧发现了这个网站,它运行得很好。

© www.soinside.com 2019 - 2024. All rights reserved.