Создание PDF — файла из формы Google с использованием шаблона Doc с помощью скрипта

#javascript #google-sheets

Вопрос:

Я использую этот скрипт для создания PDF-файла из Google с помощью шаблона в документах Google.

Сценарий, который я использую, выглядит следующим образом:

 function afterFormSubmit(e) {
    const info = e.namedValues;
    const pdfFile = createPDF(info);
    const entryRow = e.range.getRow();
    const ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2")
    ws.getRange(entryRow, 63).setValue(pdfFile.getUrl());
    ws.getRange(entryRow, 64).setValue(pdfFile.getName());
    
    sendEmail(e.namedValues ['Email address'][0],pdfFile);
}


function sendEmail(email,pdfFile){
  
  GmailApp.sendEmail(email, "Daily Transation Summary Report", "Please find the attached DTR", {
    attachments : [pdfFile],
    name: 'My Company'
});

}  
  
function createPDF(info) {
  
  const pdfFolder = DriveApp.getFolderById("1ebglel6vwMGXByeG4wHBBvJu9u0zJeMJ");
  const tempFolder = DriveApp.getFolderById("1ebglel6vwMGXByeG4wHBBvJu9u0zJeMJ");
  const templateDoc = DriveApp.getFileById("1kyFimRMdHQZV85F5P6JyCHv1DQ3KJFv1hx5o7lIcNZo");
  
  const newTempFile = templateDoc.makeCopy(tempFolder);
  const openDoc = DocumentApp.openById(newTempFile.getId());
  const body = openDoc.getBody();
  body.replaceText("{Name of Person}", info['Name of Person'][0]);
  body.replaceText("{Date of Report}", info['Date of Report'][0]);
  body.replaceText("{Name of Outlet}", info['Name of Outlet'][0]);
  body.replaceText("{Opening Petty Cash Balance}", info['Opening Petty Cash Balance'][0]);
  body.replaceText("{Total Petty Cash Received}", info['Total Petty Cash Received'][0]);
  body.replaceText("{Closing Petty Cash Balance}", info['Closing Petty Cash Balance'][0]);
  body.replaceText("{Total Petty Cash Paid}", info['Total Petty Cash Paid'][0]);
  body.replaceText("{Available Float Cash Balance}", info['Available Float Cash Balance'][0]);
  body.replaceText("{Milk For Outlet}", info['Milk For Outlet'][0]);
  body.replaceText("{Staff Milk/Toast etc.}", info['Staff Milk/Toast etc.'][0]);
  body.replaceText("{Petrol Expenses}", info['Petrol Expenses'][0]);
  body.replaceText("{Water Tank Charges}", info['Water Tank Charges'][0]);
  body.replaceText("{Repair And Maintenance}", info['Repair And Maintenance'][0]);
  body.replaceText("{Freight Paid}", info['Freight Paid'][0]);
  body.replaceText("{Purchase of Soya Chaap}", info['Purchase of Soya Chaap'][0]);
  body.replaceText("{Purchase of Rumali Roti}", info['Purchase of Rumali Roti'][0]);
  body.replaceText("{Purchase of Egg Tray}", info['Purchase of Egg Tray'][0]);
  body.replaceText("{Other Expenses}", info['Other Expenses'][0]);
  body.replaceText("{Total Tip Amount (PAYTM amp; CARD)}", info['Total Tip Amount (PAYTM amp; CARD)'][0]);
  body.replaceText("{Cash Sales - Outlet}", info['Cash Sales - Outlet'][0]);
  body.replaceText("{Cash Sales - KCCO App}", info['Cash Sales - KCCO App'][0]);
  body.replaceText("{Card Sales}", info['Card Sales'][0]);
  body.replaceText("{Credit (Udhar) Sales}", info['Credit (Udhar) Sales'][0]);
  body.replaceText("{Paytm Sales}", info['Paytm Sales'][0]);
  body.replaceText("{KCCO App Sales Razor Pay}", info['KCCO App Sales Razor Pay'][0]);
  body.replaceText("{Swiggy Sales}", info['Swiggy Sales'][0]);
  body.replaceText("{Zomato Sales}", info['Zomato Sales'][0]);
  body.replaceText("{Dunzo Sales}", info['Dunzo Sales'][0]);
  body.replaceText("{Zomato Gold Sales}", info['Zomato Gold Sales'][0]);
  body.replaceText("{Dine Out Sales}", info['Dine Out Sales'][0]);
  body.replaceText("{Total Cancelled Bill Amount}", info['Total Cancelled Bill Amount'][0]);
  body.replaceText("{Total Sales of the Day (Total of Above)}", info['Total Sales of the Day (Total of Above)'][0]);
  body.replaceText("{Total Sales of the Day (As Per PetPooja)}", info['Total Sales of the Day (As Per PetPooja)'][0]);
  body.replaceText("{Old Due Receipts  - Cash}", info['Old Due Receipts  - Cash'][0]);
  body.replaceText("{Old Due Receipts - Other Modes}", info['Old Due Receipts - Other Modes'][0]);
  body.replaceText("{Tip Receipts - Card}", info['Tip Receipts - Card'][0]);
  body.replaceText("{Tip Receipts - Paytm}", info['Tip Receipts - Paytm'][0]);
  body.replaceText("{Currency Note of INR 2000}", info['Currency Note of INR 2000'][0]);
  body.replaceText("{Currency Note of INR 500}", info['Currency Note of INR 500'][0]);
  body.replaceText("{ Currency Note of INR 200}", info[' Currency Note of INR 200'][0]);
  body.replaceText("{Currency Note of INR 100}", info['Currency Note of INR 100'][0]);
  body.replaceText("{Currency Note of INR 50}", info['Currency Note of INR 50'][0]);
  body.replaceText("{Currency Note of INR 20}", info['Currency Note of INR 20'][0]);
  body.replaceText("{Currency Note of INR 10}", info['Currency Note of INR 10'][0]);
  body.replaceText("{Other Currency Note/Coins}", info['Other Currency Note/Coins'][0]);
  body.replaceText("{Total Available Cash to Handover}", info['Total Available Cash to Handover'][0]);
  body.replaceText("{S.No.//Name of Person// Mobile No// Credit Approval By// Bill No// Total Amount of Credit", info['S.No.//Name of Person// Mobile No// Credit Approval By// Bill No// Total Amount of Credit'][0]);
  body.replaceText("{Total No. of Bills of Credit Recovery}", info['Total No. of Bills of Credit Recovery'][0]);
  body.replaceText("{S.No.//Name of Person// Mobile No// Mode of Payment// Bill No// Total Amount Received}", info['S.No.//Name of Person// Mobile No// Mode of Payment// Bill No// Total Amount Received'][0]);
  body.replaceText("{Total No. of Complementary Bills  During the Day}", info['Total No. of Complementary Bills  During the Day'][0]);
  body.replaceText("{S.No.//Name of Person// Mobile No//Reason// Bill No//Amount Settled}", info['S.No.//Name of Person// Mobile No//Reason// Bill No//Amount Settled'][0]);
  body.replaceText("{Total No. of Cancelled Bills During the Day}", info['Total No. of Cancelled Bills During the Day'][0]);
  body.replaceText("{S.No.//Name of Person// Mobile No// Bill No// Bill Amount}", info['S.No.//Name of Person// Mobile No// Bill No// Bill Amount'][0]);
  body.replaceText("{S.No.// Bill No// Mode of Payment//Tip Amount Received}", info['S.No.// Bill No// Mode of Payment//Tip Amount Received'][0]);
  body.replaceText("{No. of Cylinders Received at Outlet}", info['No. of Cylinders Received at Outlet'][0]); 
  
  openDoc.saveAndClose();
  
  const blobPDF = newTempFile.getAs(MimeType.PDF);
  const pdfFile = pdfFolder.createFile(blobPDF).setName(info['Name of Outlet'][0]  " "   info['Date of Report'][0]);
  tempFolder.removeFile(newTempFile);
    
  return pdfFile;
  
}                                         
 

Этот скрипт не генерирует PDF, а также PDF не отправляется по почте.

Ссылка на электронную таблицу приведена ниже

https://docs.google.com/spreadsheets/d/1m6Aca0TcLf5UZ7P9CvAdQDokoazQljsqDT6CGh0K3j4/edit?usp=sharing

Пожалуйста, ведите.

Комментарии:

1. От This script is not generating PDF as well PDF is not being Mailed. , я подумал, что ошибка, возможно, уже произошла в const pdfFile = createPDF(info); . Итак, если произойдет ошибка, можете ли вы показать сообщение об ошибке?

2. Ошибка типа: Не удается прочитать свойство ‘namedValues’ неопределенного значения в afterFormSubmit(Код:2:20)

3. Спасибо, что ответили. Начиная с TypeError: Cannot read property 'namedValues' of undefined at afterFormSubmit(Code:2:20) того момента , когда вы непосредственно запустили функцию afterFormSubmit в редакторе сценариев, возникает такая ошибка. Потому что объект события e не задан. Когда я увидел ваш сценарий, я подумал, что вы хотели создать свой сценарий для выполнения сценария с помощью триггера отправки формы. Как насчет этого?

4. ДА.. Я хочу создать PDF-файл, когда пользователь отправит форму. Для этого я также добавил триггер при отправке формы.

5. это показывает эту ошибку при отправке формы…Ошибка типа: Не удается прочитать свойство » 0 » неопределенного в CreatePDF(Код:39:64) при отправке формы(Код:3:21)