如何通过Google Apps Script实现Google Docs指定页面PDF导出及模板适配
Got it, let's walk through exactly how to build this solution step by step. You’ve got three main goals here: handling Google Form submissions, exporting specific pages from Google Docs as PDFs (using two separate templates), and sending the right email based on whether the user picked standard or non-standard parts. Let’s break it down.
First, let’s get your templates and form set up properly:
- Create two Google Doc templates:
- Template 1 (Standard Part Quote): Grab its document ID from the URL (the string between
d/and/editin the Doc’s address bar) - Template 2 (Non-Standard Request Confirmation): Same thing—save its document ID for later
- Template 1 (Standard Part Quote): Grab its document ID from the URL (the string between
- In your Google Form, add a single-select question (name it something like "Part Type") with options:
Standard PartandNon-Standard Part. Also make sure you have a field to collect the user’s email address.
Google Docs doesn’t have a direct API to export specific pages, but we can work around this by making a temporary copy of the template, deleting the pages we don’t need, then exporting the trimmed version as a PDF. Here’s the code for that:
function exportSpecificPagesAsPDF(docId, startPage, endPage) { // Make a temporary copy of the template to avoid modifying the original const tempDoc = DriveApp.getFileById(docId).makeCopy('Temp_PDF_Export'); const tempDocId = tempDoc.getId(); const doc = DocumentApp.openById(tempDocId); const body = doc.getBody(); const allElements = body.getPageElements(); // Remove content before the start page if (startPage > 1) { let elementsToDelete = []; let currentPage = 1; for (let i = 0; i < allElements.length; i++) { const element = allElements[i]; elementsToDelete.push(element); // Check for page breaks to track page changes if (element.getType() === DocumentApp.ElementType.PAGE_BREAK) { currentPage++; if (currentPage === startPage) break; } } elementsToDelete.forEach(el => el.removeFromParent()); } // Remove content after the end page let currentPage = startPage; let elementsToDelete = []; for (let i = 0; i < allElements.length; i++) { const element = allElements[i]; if (currentPage > endPage) elementsToDelete.push(element); if (element.getType() === DocumentApp.ElementType.PAGE_BREAK) currentPage++; } elementsToDelete.forEach(el => el.removeFromParent()); // Save the trimmed temp doc and export as PDF doc.saveAndClose(); const pdfBlob = tempDoc.getAs('application/pdf'); // Clean up the temporary file DriveApp.getFileById(tempDocId).setTrashed(true); return pdfBlob; }
This function takes your template ID, start page, and end page, then returns a PDF blob ready to attach to an email.
Next, we’ll write a function that triggers when someone submits the form. It’ll grab the response data, pick the right template, generate the PDF, and send the email.
function onFormSubmit(e) { // Pull data from the form submission const formResponse = e.response; const itemResponses = formResponse.getItemResponses(); let partType = ''; let recipientEmail = ''; // Add variables here for other form fields you want to use (e.g., customer name, part details) // Loop through responses to extract key info for (const itemResponse of itemResponses) { const questionTitle = itemResponse.getItem().getTitle(); if (questionTitle === 'Part Type') { partType = itemResponse.getResponse(); } else if (questionTitle === 'Your Email') { // Replace with your form's email field name recipientEmail = itemResponse.getResponse(); } // Add else if blocks here to capture other form data } // Set up template, PDF, and email details based on part type let pdfBlob; let emailSubject; let emailBody; if (partType === 'Standard Part') { const standardTemplateId = 'YOUR_STANDARD_TEMPLATE_ID'; // Replace with your Template 1 ID pdfBlob = exportSpecificPagesAsPDF(standardTemplateId, 1, 1); // Adjust page range as needed emailSubject = 'Your Standard Part Quote is Ready'; emailBody = 'Hi there,\n\nAttached is your requested standard part quote. Let us know if you have questions!\n\nBest regards,'; } else if (partType === 'Non-Standard Part') { const nonStandardTemplateId = 'YOUR_NON_STANDARD_TEMPLATE_ID'; // Replace with your Template 2 ID pdfBlob = exportSpecificPagesAsPDF(nonStandardTemplateId, 1, 1); // Adjust page range as needed emailSubject = 'We’ve Received Your Non-Standard Part Request'; emailBody = 'Hi there,\n\nThanks for reaching out! We’ve received your non-standard part request and will follow up with you shortly.\n\nBest regards,'; } // Send the email with the PDF attachment if (recipientEmail && pdfBlob) { MailApp.sendEmail({ to: recipientEmail, subject: emailSubject, body: emailBody, attachments: [pdfBlob.setName(`Document_${new Date().toISOString().slice(0,10)}.pdf`)] }); } }
To make this run automatically when someone submits the form:
- Open the Apps Script editor from your Google Form (click Extensions > Apps Script)
- Click the clock icon (Triggers) on the left sidebar
- Click "Add Trigger"
- Configure it like this:
- Choose function to run:
onFormSubmit - Deployment:
Head - Event source:
Form - Event type:
On form submit
- Choose function to run:
- Save the trigger and authorize the required permissions (you’ll need to allow access to Drive, Docs, and Mail)
- Page Tracking: The code uses page breaks to count pages—make sure your templates use manual page breaks (Insert > Break > Page break) to define page boundaries.
- Template Filling: If you want to populate the template with form data (like a customer’s name), add placeholders in your Doc (e.g.,
{{Customer Name}}) and usebody.replaceText('{{Customer Name}}', customerName)before exporting the PDF. - Testing: Test the function manually first by running
onFormSubmitwith a dummy response (use the "Test" button in the script editor) to make sure everything works.
内容的提问来源于stack exchange,提问作者Danial Asraf Norbee

