如何通过电子邮件发送内容以 table 格式显示的 PDF?
How to send a PDF via email with the contents displayed in table like format?
这是我现在使用的代码:
function emailQuestionnaireAsPDF(questionnaireKey) {
if (app.getActiveUserRoles().indexOf(app.roles.Admins) === -1) {
throw new Error('You don\'t have permissions to perform this operation');
}
var questionnaire = app.models.Questionnaire.getRecord(questionnaireKey);
if (!questionnaire) {
throw new Error('Questionnaire was not found');
}
var tmpDoc = DocumentApp.create(FILE_NAME + ' ' + Date.now());
var body = tmpDoc.getBody();
var title = questionnaire.FirstName + '\'s Questionnaire';
var fields = app.metadata.models.Questionnaire.fields;
body.insertParagraph(0, title)
.setHeading(DocumentApp.ParagraphHeading.HEADING1)
.setAlignment(DocumentApp.HorizontalAlignment.CENTER);
appendField_(body, fields.FirstName.displayName,
questionnaire.FirstName);
appendField_(body, fields.LastName.displayName,
questionnaire.LastName);
appendField_(body, fields.LikeIceCream.displayName,
questionnaire.LikeIceCream);
appendField_(body, fields.FavoriteMovie.displayName,
questionnaire.FavoriteMovie);
appendField_(body, fields.FavoriteColor.displayName,
questionnaire.FavoriteColor);
appendField_(body, fields.LuckyNumber.displayName,
questionnaire.LuckyNumber);
tmpDoc.saveAndClose();
var blob = tmpDoc.getAs(MimeType.PDF);
var pdfFile = DriveApp.createFile(blob);
Drive.Files.remove(tmpDoc.getId());
pdfFile.setName(FILE_NAME);
sendEmail_(Session.getActiveUser().getEmail(), FILE_NAME, pdfFile.getUrl());
}
我正在尝试将与调查问卷相关的模型中的所有字段附加到 "pdfFile"。这是如何以一种方式完成的,所有关联的字段和值都以类似 table 的格式粘贴到 pdfFile 中?
根据您的描述,我是这样做的:
创建了一个名为 问卷 的模型,其中包含以下字段:
- 名字
- 姓氏
- 喜欢冰淇淋
- 最喜欢的电影
- 最喜欢的颜色
- 幸运数
我添加了一些测试记录。然后在服务器脚本上我添加了两个函数。第一个发送电子邮件的人如下所示:
function sendEmail(recipient, fileUrl, fileName){
var pdfBlob = UrlFetchApp.fetch(fileUrl).getAs("application/pdf");
MailApp.sendEmail({
to: recipient,
subject: "PDF Email Sample",
htmlBody: "Attached the PDF File",
attachments: [pdfBlob]
});
}
生成文档的第二个函数如下所示:
function emailQuestionnaireAsPDF(questionnaireKey){
if (app.getActiveUserRoles().indexOf(app.roles.Admins) === -1) {
throw new Error('You don\'t have permissions to perform this operation');
}
var questionnaire = app.models.questionnaire.getRecord(questionnaireKey);
if (!questionnaire) {
throw new Error('Questionnaire was not found');
}
//Start generating the HTML template
var htmlData = "";
htmlData += "<h1 style='text-align:center'>" + questionnaire.firstName + "'s Questionnaire </h1><br>"; //Title of the document
//Create table start tag
htmlData += "<table style='border:none;'>";
//Create headers and append to table
var headers = ["QUESTION", "RESPONSE"];
var hRowStyle = "background-color:#efefef"; //style for table header row
var hCellStyle = "font-weight:bold; padding-top:4px; padding-bottom: 3px; border-bottom:1px solid #bebebe;"; //style for table header cells
htmlData += "<tr style='"+hRowStyle+"'><td style='"+hCellStyle+"'>" + headers.join("</td><td style='"+hCellStyle+"'>") + "</td></tr>";
//Define row cell styles
var tdSytle = "border-bottom: 1px solid #bebebe; border-left:0px; border-right:0px; padding-top:7px; padding-bottom: 6px;";
//Create table rows
var rows = [];
rows.push(["First Name:", questionnaire.firstName]); // Add firstName
rows.push(["Last Name:", questionnaire.lastName]); // Add lastName
rows.push(["Likes Icecream:", questionnaire.likeIcecream]); // Add likeIceacream
rows.push(["Favorite Movie:", questionnaire.favoriteMovie]); // Add favoriteMovie
rows.push(["Favorite Color:", questionnaire.favoriteColor]); // Add favoriteColor
rows.push(["Lucky Number:", questionnaire.luckyNumber]); // Add luckyNumber
//Append rows to table
rows.forEach(function(row){
htmlData += "<tr><td style='"+tdSytle+"'>" + row.join("</td><td style='"+tdSytle+"'>") + "</td><tr>";
});
//Create table end tag
htmlData += "</table>";
//Create gooleDriveDoc
var fileName = questionnaire.firstName + "'s Questionnaire";
var data = Utilities.newBlob("").setDataFromString(htmlData).setContentType("text/html");
var drvFile = Drive.Files.insert({title: fileName}, data, {convert: true});
//Mail PDF File
var recipient = "email@test.com";
var fileUrl = "https://docs.google.com/document/d/"+drvFile.id+"/export?format=pdf&access_token="+ScriptApp.getOAuthToken();
sendEmail(recipient, fileUrl, fileName);
}
总而言之,我从 HTML 模板创建了一个 google 文档。然后,我使用带有访问令牌的下载 url 来获取 pdf Blob 并将其附加到电子邮件中。
结果如下:
通读代码,您应该能够详细了解它正在做什么,当然,您可以改进它!
参考:
- https://developers.google.com/drive/api/v2/reference/files/insert
- https://developers.google.com/apps-script/reference/mail/mail-app#sendEmail(String,String,String,Object)
- https://developers.google.com/apps-script/reference/base/blob
- https://developers.google.com/identity/protocols/OAuth2WebServer#callinganapi
- https://developers.google.com/apps-script/reference/script/script-app#getoauthtoken
- https://developers.google.com/drive/api/v2/reference/files/get
- https://www.labnol.org/internet/direct-links-for-google-drive/28356/
这是我现在使用的代码:
function emailQuestionnaireAsPDF(questionnaireKey) {
if (app.getActiveUserRoles().indexOf(app.roles.Admins) === -1) {
throw new Error('You don\'t have permissions to perform this operation');
}
var questionnaire = app.models.Questionnaire.getRecord(questionnaireKey);
if (!questionnaire) {
throw new Error('Questionnaire was not found');
}
var tmpDoc = DocumentApp.create(FILE_NAME + ' ' + Date.now());
var body = tmpDoc.getBody();
var title = questionnaire.FirstName + '\'s Questionnaire';
var fields = app.metadata.models.Questionnaire.fields;
body.insertParagraph(0, title)
.setHeading(DocumentApp.ParagraphHeading.HEADING1)
.setAlignment(DocumentApp.HorizontalAlignment.CENTER);
appendField_(body, fields.FirstName.displayName,
questionnaire.FirstName);
appendField_(body, fields.LastName.displayName,
questionnaire.LastName);
appendField_(body, fields.LikeIceCream.displayName,
questionnaire.LikeIceCream);
appendField_(body, fields.FavoriteMovie.displayName,
questionnaire.FavoriteMovie);
appendField_(body, fields.FavoriteColor.displayName,
questionnaire.FavoriteColor);
appendField_(body, fields.LuckyNumber.displayName,
questionnaire.LuckyNumber);
tmpDoc.saveAndClose();
var blob = tmpDoc.getAs(MimeType.PDF);
var pdfFile = DriveApp.createFile(blob);
Drive.Files.remove(tmpDoc.getId());
pdfFile.setName(FILE_NAME);
sendEmail_(Session.getActiveUser().getEmail(), FILE_NAME, pdfFile.getUrl());
}
我正在尝试将与调查问卷相关的模型中的所有字段附加到 "pdfFile"。这是如何以一种方式完成的,所有关联的字段和值都以类似 table 的格式粘贴到 pdfFile 中?
根据您的描述,我是这样做的:
创建了一个名为 问卷 的模型,其中包含以下字段:
- 名字
- 姓氏
- 喜欢冰淇淋
- 最喜欢的电影
- 最喜欢的颜色
- 幸运数
我添加了一些测试记录。然后在服务器脚本上我添加了两个函数。第一个发送电子邮件的人如下所示:
function sendEmail(recipient, fileUrl, fileName){
var pdfBlob = UrlFetchApp.fetch(fileUrl).getAs("application/pdf");
MailApp.sendEmail({
to: recipient,
subject: "PDF Email Sample",
htmlBody: "Attached the PDF File",
attachments: [pdfBlob]
});
}
生成文档的第二个函数如下所示:
function emailQuestionnaireAsPDF(questionnaireKey){
if (app.getActiveUserRoles().indexOf(app.roles.Admins) === -1) {
throw new Error('You don\'t have permissions to perform this operation');
}
var questionnaire = app.models.questionnaire.getRecord(questionnaireKey);
if (!questionnaire) {
throw new Error('Questionnaire was not found');
}
//Start generating the HTML template
var htmlData = "";
htmlData += "<h1 style='text-align:center'>" + questionnaire.firstName + "'s Questionnaire </h1><br>"; //Title of the document
//Create table start tag
htmlData += "<table style='border:none;'>";
//Create headers and append to table
var headers = ["QUESTION", "RESPONSE"];
var hRowStyle = "background-color:#efefef"; //style for table header row
var hCellStyle = "font-weight:bold; padding-top:4px; padding-bottom: 3px; border-bottom:1px solid #bebebe;"; //style for table header cells
htmlData += "<tr style='"+hRowStyle+"'><td style='"+hCellStyle+"'>" + headers.join("</td><td style='"+hCellStyle+"'>") + "</td></tr>";
//Define row cell styles
var tdSytle = "border-bottom: 1px solid #bebebe; border-left:0px; border-right:0px; padding-top:7px; padding-bottom: 6px;";
//Create table rows
var rows = [];
rows.push(["First Name:", questionnaire.firstName]); // Add firstName
rows.push(["Last Name:", questionnaire.lastName]); // Add lastName
rows.push(["Likes Icecream:", questionnaire.likeIcecream]); // Add likeIceacream
rows.push(["Favorite Movie:", questionnaire.favoriteMovie]); // Add favoriteMovie
rows.push(["Favorite Color:", questionnaire.favoriteColor]); // Add favoriteColor
rows.push(["Lucky Number:", questionnaire.luckyNumber]); // Add luckyNumber
//Append rows to table
rows.forEach(function(row){
htmlData += "<tr><td style='"+tdSytle+"'>" + row.join("</td><td style='"+tdSytle+"'>") + "</td><tr>";
});
//Create table end tag
htmlData += "</table>";
//Create gooleDriveDoc
var fileName = questionnaire.firstName + "'s Questionnaire";
var data = Utilities.newBlob("").setDataFromString(htmlData).setContentType("text/html");
var drvFile = Drive.Files.insert({title: fileName}, data, {convert: true});
//Mail PDF File
var recipient = "email@test.com";
var fileUrl = "https://docs.google.com/document/d/"+drvFile.id+"/export?format=pdf&access_token="+ScriptApp.getOAuthToken();
sendEmail(recipient, fileUrl, fileName);
}
总而言之,我从 HTML 模板创建了一个 google 文档。然后,我使用带有访问令牌的下载 url 来获取 pdf Blob 并将其附加到电子邮件中。
结果如下:
通读代码,您应该能够详细了解它正在做什么,当然,您可以改进它!
参考:
- https://developers.google.com/drive/api/v2/reference/files/insert
- https://developers.google.com/apps-script/reference/mail/mail-app#sendEmail(String,String,String,Object)
- https://developers.google.com/apps-script/reference/base/blob
- https://developers.google.com/identity/protocols/OAuth2WebServer#callinganapi
- https://developers.google.com/apps-script/reference/script/script-app#getoauthtoken
- https://developers.google.com/drive/api/v2/reference/files/get
- https://www.labnol.org/internet/direct-links-for-google-drive/28356/