I’m currently on my third project using Google Apps Script, but I have encountered one last issue. My goal is to generate a PDF automatically with the data collected from a Google Form, then send this PDF via email.
So far, everything is set up correctly except for the fact that the PDF still contains placeholder text, like {staff}, instead of the actual data from the spreadsheet.
Here’s my existing code:
function generateReport(){
const spreadsheetId = 'sheet-id-987654321';
const workbook = SpreadsheetApp.openById(spreadsheetId);
const worksheet = workbook.getSheetByName('Report-Info');
const records = worksheet.getDataRange().getDisplayValues().slice(1);
const mailTemplate = HtmlService.createTemplateFromFile('notification.html');
const reportTemplate = HtmlService.createTemplateFromFile('reportLayout.html');
records.forEach((record,index)=>{
const employeeName = record[0];
const reviewId = record[4];
const recipient = {
StaffName: employeeName,
ReviewDate: record[2]
};
mailTemplate.recipient = recipient;
mailTemplate.id = reviewId;
reportTemplate['staff'] = record[0];
reportTemplate['date'] = record[1];
reportTemplate['period'] = record[2];
reportTemplate['id'] = reviewId;
reportTemplate['category'] = record[5];
reportTemplate['score'] = record[6];
reportTemplate['item1'] = record[7];
reportTemplate['item2'] = record[8];
reportTemplate['item3'] = record[10];
const emailContent = mailTemplate.evaluate().getContent();
const pdfContent = reportTemplate.evaluate().getContent();
const pdfFile = Utilities.newBlob(pdfContent, MimeType.HTML).getAs(MimeType.PDF);
pdfFile.setName(record[0] + '_' + record[1] + '.pdf');
const recipientEmail = record[3];
const emailSubject = 'Performance Report for ' + record[0];
MailApp.sendEmail({
to: recipientEmail,
subject: emailSubject,
htmlBody: emailContent,
attachments: [pdfFile]
});
});
}
HTML template structure:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div style="font-family: Arial; font-size: 12px;">
<table style="width: 100%;">
<tr>
<td style="text-align: center;">
<h2>Performance Review</h2>
</td>
<td style="text-align: right;">
<p>Employee: {staff}</p>
<p>Review Date: {date}</p>
<p>Period: {period}</p>
<p>ID Number: {id}</p>
<p>Category: {category}</p>
<p>Final Score: {score}</p>
</td>
</tr>
</table>
<hr>
<h4>Performance Items</h4>
<p>Communication skills rating: {item1}</p>
<p>Task completion assessment: {item2}</p>
<p>Team collaboration score: {item3}</p>
</div>
</body>
</html>
The placeholders like {staff} and {date} aren’t getting replaced with actual spreadsheet values. I’ve tried using Google Docs as templates and creating PDFs directly in code but same problem. Any ideas what I’m missing?