If you have ever managed or developed for an enterprise Adobe Commerce (Magento 2) store, you already know the collective groan that echoes through the engineering team whenever the finance department asks for a "quick change" to the invoice layout.
Magento’s native PDF invoicing system is notoriously rigid. It belongs to an era where visual layouts were bound tightly to backend PHP code. Want to change a font? Want to shift a table column to make room for a Purchase Order (PO) number? Or maybe add a secondary logo for a new regional tax compliance rule?
Under normal circumstances, that "quick change" turns into a developer spending hours writing complex Zend PDF layout override classes.
In a B2B ecosystem, an invoice isn't just a receipt—it’s a dynamic legal document. It needs to reflect specific net terms, custom tax exemptions, and changing banking details on the fly.
What if we could completely decouple document design from the core e-commerce codebase and hand total layout control back to the non-technical operations team?
Here is how we can build a template-driven document generation factory using Google Apps Script.
The Architecture: A Lightweight Cloud Pipeline
Instead of forcing Magento to render heavy PDFs natively, we can offload the visual heavy lifting to Google Workspace. The flow operates in four seamless steps:
- The Trigger: Magento fires an order Webhook immediately after a B2B checkout is completed.
-
The Catch: A Google Apps Script web app receives the secure JSON payload via a
doPost(e)hook. -
The Factory: Apps Script clones a "Master Invoice Template" inside Google Drive, identifies custom placeholder tags (like
{{ORDER_ID}}), and swaps them out with real-time order data using regex. -
The Delivery: The script compiles the document into a crisp PDF blob and fires it directly to the customer's inbox using
GmailApp.
Step 1: Crafting the Visual Blueprint in Google Docs
The beauty of this setup lies in its simplicity. You don't write HTML or CSS for your layout. You simply open Google Docs and design your invoice.
Wherever dynamic data from Magento needs to live, you drop a placeholder tag wrapped in double curly braces:
{{ORDER_ID}}{{CUSTOMER_NAME}}{{GRAND_TOTAL}}{{DATE}}
Once the design is finalized, note the Document ID from the browser URL (the long alphanumeric string between /d/ and /edit).
Step 2: The Core Apps Script Blueprint
Open Google Apps Script and write the core worker function to handle the duplication, replacement, and emailing logic.
// Code.gs
// The ID of your beautiful Google Doc template
const TEMPLATE_DOC_ID = "YOUR_MASTER_TEMPLATE_DOCUMENT_ID";
// The ID of the Google Drive Folder where generated PDFs should be archived
const OUTPUT_FOLDER_ID = "YOUR_ARCHIVE_FOLDER_ID";
function generateAndEmailInvoice(orderData) {
// 1. Fetch the master template and target archive folder
const templateDoc = DriveApp.getFileById(TEMPLATE_DOC_ID);
const outputFolder = DriveApp.getFolderById(OUTPUT_FOLDER_ID);
// 2. Clone the template dynamically for the specific order
const newFilename = `Invoice_${orderData.increment_id}_${orderData.customer_name}`;
const tempDocFile = templateDoc.makeCopy(newFilename, outputFolder);
const tempDocId = tempDocFile.getId();
// 3. Open the newly created document to modify text
const doc = DocumentApp.openById(tempDocId);
const body = doc.getBody();
// 4. Execute regex replacements for placeholder tags
body.replaceText("{{ORDER_ID}}", orderData.increment_id);
body.replaceText("{{CUSTOMER_NAME}}", orderData.customer_name);
body.replaceText("{{GRAND_TOTAL}}", "$" + parseFloat(orderData.grand_total).toFixed(2));
// Format the execution date cleanly
const today = Utilities.formatDate(new Date(), "GMT", "MMMM dd, yyyy");
body.replaceText("{{DATE}}", today);
// Save and flush changes to ensure PDF conversion catches everything
doc.saveAndClose();
// 5. Convert the tailored Doc into a PDF blob
const pdfBlob = tempDocFile.getAs(MimeType.PDF);
pdfBlob.setName(`Invoice_${orderData.increment_id}.pdf`);
// 6. Dispatch the email via GmailApp
const emailSubject = `Your Invoice for Order #${orderData.increment_id}`;
const emailBody = `Hi ${orderData.customer_name},\n\nThank you for your business. Please find your official B2B invoice attached.\n\nBest regards,\nBilling Department`;
GmailApp.sendEmail(orderData.customer_email, emailSubject, emailBody, {
attachments: [pdfBlob],
name: "Billing Department"
});
// Optional: Clean up Google Drive by trashing the temporary Doc clone
// tempDocFile.setTrashed(true);
Logger.log("Invoice successfully generated and sent to " + orderData.customer_email);
}
To bridge this with Magento, we map our web app entry point directly to this routine:
function doPost(e) {
const payload = JSON.parse(e.postData.contents);
// ... Basic security and origin verification checks go here ...
// Pass the incoming webhook data straight to the engine
generateAndEmailInvoice(payload.order_data);
return ContentService.createTextOutput("Success");
}
The Real Win: True Architectural Freedom
Think about the paradigm shift this introduces to your e-commerce workflow.
If your legal or accounting department decides next Tuesday that they need to append a mandatory "Late Payment Penalty Warning" to the footer of every invoice, they do not need to call a developer. They don't need to request a code deployment, wait for a staging QA cycle, or touch a command line.
An administrator simply opens the shared Google Doc template, types the new text block, changes the font color to bold red, and hits close.
The next Magento checkout webhook that hits the cloud pipeline minutes later will automatically render the new disclaimer on the fly.
By utilizing Google Workspace as a dynamic rendering engine, you completely decouple content representation from your e-commerce platform's core architecture. No more fighting legacy PDF libraries.
If you want to dive deeper into custom Magento 2 automations, webhooks, or scalable Google Workspace integrations, the full implementation patterns and boilerplate extensions are available on the official MageSheet blog: [https://magesheet.com/blog/magento-automated-invoice-google-docs]
Top comments (0)