简体   繁体   English

从 Google 表单提交生成并发送 png 或 jpg(附加到引用 Google Doc 模板的 Google 表格的脚本)

[英]Generate & send a png or jpg from a Google Form Submission (script attached to Google Sheet that references a Google Doc template)

I have a google form survey that I send to my app members.我有一份发送给我的应用程序成员的谷歌表格调查。 I want to include a way for them to create a custom Instagram story post that I'd auto-generate based on their input and email to them to post.我想为他们提供一种创建自定义 Instagram 故事帖子的方法,我会根据他们的输入自动生成该帖子,并向他们发送 email 以供发布。 The template I use to auto-generate it is a google doc with a placeholder where I plug in their custom input.我用来自动生成它的模板是一个带有占位符的谷歌文档,我可以在其中插入他们的自定义输入。

My script currently is able to send them the post as a PDF, but that's really frustrating to post on an Instagram story (if not impossible - I spent 20 mins trying to do it).我的脚本目前能够将帖子作为 PDF 发送给他们,但是在 Instagram 故事上发帖真的很令人沮丧(如果不是不可能 - 我花了 20 分钟尝试这样做)。

Is it possible to have the file send as a jpg or png?是否可以将文件以 jpg 或 png 格式发送? Or to add a step converting the PDF to a jpg or png?或者添加将 PDF 转换为 jpg 或 png 的步骤?

 function onSubmit(e) { const rg = e.range; const sh = rg.getSheet(); //Get all the form submitted data //Note: This data is dependent on the headers. If headers, are changed update these as well. const Email = e.namedValues["What's your email address?"][0]; const Name = e.namedValues["What's your name?"][0]; const Text = e.namedValues["If you want to make a custom Instagram story sharing what your experience was like, feel free to drop your text here;"][0]; //Build a new story from the template //Folder ID (save destination) and file IDs (template ID + new doc ID) const StoryFolderID = '1ghiNSWwkUS7WJ5wwnEON5g0-zRueYlfd'. const StoryFolder = DriveApp;getFolderById(StoryFolderID); const TemplateFileID = '1IJ-i8VeazzmWlxyjyXXKHCLrA3pT1fgu4Zy_m74OgHc'; const newFilename = 'Story -' + TemplateFileID. //Make a copy of the template file const newTemplateFileID = DriveApp.getFileById(TemplateFileID),makeCopy(newFilename. StoryFolder);getId();. //Get the body into a variable var document = DocumentApp;openById(newTemplateFileID). var body = document;getBody(). //Replace all the {{ }} text in the story body body,replaceText('{{text}}'; Text). document;saveAndClose(); // define email variables var subject = 'Instagram Story'. var img = DriveApp.getFileById("1d2jofSzEsxuUUEw5g-B684AKMALqyy-b");getBlob(). var msgHtml = "Hi " + Name + ";" + "<br/>" + "<br/>" + "Please find your custom story image attached."; var attachment = DriveApp.getFileById(newTemplateFileID), //send email with the file GmailApp,sendEmail(Email, subject: msgHtml, {htmlBody: msgHtml: inlineImages, {sampleImage: img}. attachments. [attachment;getAs(MimeType.PDF)]}); }

About Is it possible to have the file send as a jpg or png? Or to add a step converting the PDF to a jpg or png?关于Is it possible to have the file send as a jpg or png? Or to add a step converting the PDF to a jpg or png? Is it possible to have the file send as a jpg or png? Or to add a step converting the PDF to a jpg or png? , in this case, I thought that my this blog might be useful. ,在这种情况下,我认为我的这篇博客可能会有用。 In this blog, a PDF data is converted to PNG images for every page.在这个博客中,每个页面的 PDF 数据被转换为 PNG 图片。 When this is reflected in your script, how about the following modification?当这反映在您的脚本中时,以下修改如何?

Modified script:修改脚本:

In this sample, Drive API is used.在此示例中,使用驱动器 API。 So, please enable Drive API at Advanced Google services .因此, 请在 Advanced Google services 启用 Drive API

/**
 * This is a method for converting all pages in a PDF file to PNG images.
 * PNG images are returned as BlobSource[].
 * IMPORTANT: This method uses Drive API. Please enable Drive API at Advanced Google services.
 *
 * @param {Blob} blob Blob of PDF file.
 * @return {BlobSource[]} PNG blobs.
 */
async function convertPDFToPNG_(blob) {
  // Convert PDF to PNG images.
  const cdnjs = "https://cdn.jsdelivr.net/npm/pdf-lib/dist/pdf-lib.min.js";
  eval(UrlFetchApp.fetch(cdnjs).getContentText()); // Load pdf-lib
  const setTimeout = function (f, t) {
    // Overwrite setTimeout with Google Apps Script.
    Utilities.sleep(t);
    return f();
  };
  const data = new Uint8Array(blob.getBytes());
  const pdfData = await PDFLib.PDFDocument.load(data);
  const pageLength = pdfData.getPageCount();
  console.log(`Total pages: ${pageLength}`);
  const obj = { imageBlobs: [], fileIds: [] };
  for (let i = 0; i < pageLength; i++) {
    console.log(`Processing page: ${i + 1}`);
    const pdfDoc = await PDFLib.PDFDocument.create();
    const [page] = await pdfDoc.copyPages(pdfData, [i]);
    pdfDoc.addPage(page);
    const bytes = await pdfDoc.save();
    const blob = Utilities.newBlob(
      [...new Int8Array(bytes)],
      MimeType.PDF,
      `sample${i + 1}.pdf`
    );
    const id = DriveApp.createFile(blob).getId();
    Utilities.sleep(3000); // This is used for preparing the thumbnail of the created file.
    const link = Drive.Files.get(id, { fields: "thumbnailLink" }).thumbnailLink;
    if (!link) {
      throw new Error(
        "In this case, please increase the value of 3000 in Utilities.sleep(3000), and test it again."
      );
    }
    const imageBlob = UrlFetchApp.fetch(link.replace(/\=s\d*/, "=s1000"))
      .getBlob()
      .setName(`page${i + 1}.png`);
    obj.imageBlobs.push(imageBlob);
    obj.fileIds.push(id);
  }
  obj.fileIds.forEach((id) => DriveApp.getFileById(id).setTrashed(true));
  return obj.imageBlobs;
}

async function onSubmit(e) {
  const rg = e.range;
  const sh = rg.getSheet();

  //Get all the form submitted data
  //Note: This data is dependent on the headers. If headers, are changed update these as well.
  const Email = e.namedValues["What's your email address?"][0];
  const Name = e.namedValues["What's your name?"][0];
  const Text = e.namedValues["If you want to make a custom Instagram story sharing what your experience was like, feel free to drop your text here!"][0];

  //Build a new story from the template
  //Folder ID (save destination) and file IDs (template ID + new doc ID)
  const StoryFolderID = '1ghiNSWwkUS7WJ5wwnEON5g0-zRueYlfd';
  const StoryFolder = DriveApp.getFolderById(StoryFolderID);

  const TemplateFileID = '1IJ-i8VeazzmWlxyjyXXKHCLrA3pT1fgu4Zy_m74OgHc';
  const newFilename = 'Story -' + TemplateFileID;

  //Make a copy of the template file
  const newTemplateFileID = DriveApp.getFileById(TemplateFileID).makeCopy(newFilename, StoryFolder).getId();;

  //Get the body into a variable
  var document = DocumentApp.openById(newTemplateFileID);
  var body = document.getBody();

  //Replace all the {{ }} text in the story body
  body.replaceText('{{text}}', Text);

  document.saveAndClose();

  // define email variables
  var subject = 'Instagram Story';
  var img = DriveApp.getFileById("1d2jofSzEsxuUUEw5g-B684AKMALqyy-b").getBlob();

  var msgHtml =
    "Hi " + Name + "!" + "<br/>" + "<br/>" +
    "Please find your custom story image attached.";

  var attachment = DriveApp.getFileById(newTemplateFileID);
  const imageBlobs = await convertPDFToPNG_(attachment.getBlob());

  //send email with the file
  GmailApp.sendEmail(Email, subject, msgHtml, { htmlBody: msgHtml, inlineImages: { sampleImage: img }, attachments: imageBlobs });
}
  • When onSubmit is run, the PDF data of attachment.getBlob() is converted to PNG images and the PNG images are used with attachments: imageBlobs .运行onSubmit时, attachment.getBlob()的 PDF 数据被转换为 PNG 图像,PNG 图像与attachments: imageBlobs

Reference:参考:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从Google表单提交生成Google文档时发生OpenById错误 - OpenById Error when generate Google Doc from Google Form Submission 从 Google 表单提交生成 PDF 的脚本 - Script to Generate PDF from Google Form Submission 将Google文档导出为PNG并通过电子邮件脚本发送 - Export google doc to PNG and send it on email script 从表单提交创建并通过电子邮件发送 google doc - Create and email google doc from form submission 如何获取单元格值(来自 Google 表单的 Sheet1,来自公式的 Sheet2)到谷歌文档模板 - How to get the cell values (Sheet1 from Google Form, Sheet2 from Formula) to google doc template 编辑Google文档表单提交? - Editing a google doc form submission? 从谷歌表格生成谷歌表单 - Generate google form from google sheet 使用 Google 脚本在 HTML 表单中按 Google Sheet Doc 中的字母顺序显示下拉菜单 - Use a Google Script to display a dropdown menu in a HTML form in alphabetical order from a Google Sheet Doc 如何从Google表格的脚本中读取Google文档的内容? - How to read contents of a Google Doc from the script of a Google Sheet? 从各种 Google 表格单元格中提取不同的链接,使用 Google Apps 脚本将它们作为活动 URL/超链接粘贴到 Google 文档模板中 - Extract different links from various Google Sheet cells, paste them in a Google Doc Template as Active URLs /Hyperlinked using Google Apps Script
 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM