Back to Catalog

Create custom PDF documents from templates with Gemini & Google Drive

Ozgur KaratekeOzgur Karateke
8847 views
2/3/2026
Official Page

This workflow contains community nodes that are only compatible with the self-hosted version of n8n.

1 — What Does It Do / Which Problem Does It Solve?

This workflow turns Google Docs-based contract & form templates into ready-to-sign PDFs in minutes—all from a single chat flow.

  • Automates repetitive document creation. Instead of copying a rental, sales, or NDA template and filling it by hand every time, the bot asks for the required values and fills them in.
  • Eliminates human error. It lists every mandatory field so nothing is missed, and removes unnecessary clauses via conditional blocks.
  • Speeds up approvals. The final draft arrives as a direct PDF link—one click to send for signing.
  • One template → unlimited variations. Every new template you drop in Drive is auto-listed with **zero workflow edits—**it scales effortlessly.
  • 100 % no-code. Runs on n8n + Google Apps Script—no extra backend, self-hosted or cloud.

2 — How It Works (Detailed Flow)

  1. 📝 Template Discovery

    📂 The TemplateList node scans the Drive folder you specify via the ?mode=meta endpoint and returns an id / title / desc list. The bot shows this list in chat.

  2. 🎯 Selection & Metadata Fetch

    The user types a template name.

    🔍 GetMetaData opens the chosen Doc, extracts META_JSON, placeholders, and conditional blocks, then lists mandatory & optional fields.

  3. 🗣 Data-Collection Loop

    • The bot asks for every placeholder value.

    • For each conditional block it asks 🟢 Yes / 🔴 No.

      Answers are accumulated in a data JSON object.

  4. Final Confirmation

    The bot summarizes the inputs → when the user clicks Confirm, the DocProcess sub-workflow starts.

  5. ⚙️ DocProcess Sub-Workflow

    | 🔧 Step | Node | Task | | --- | --- | --- | | 1 | User Choice Match Check | Verifies name–ID match; throws if wrong | | 2 | GetMetaData (renew) | Gets the latest placeholder list | | 3 | Validate JSON Format | Checks for missing / unknown fields | | 4 | CopyTemplate | Copies the Doc via Drive API | | 5 | FillDocument | Apps Script fills placeholders & removes blocks | | 6 | Generate PDF Link | Builds an export?format=pdf URL |

  6. 📎 Delivery

    The master agent sends 🔗 Download PDF & ✏️ Open Google Doc links.

  7. 🚫 Error Paths

    • status:"ERROR", missing:[…] → bot lists missing fields and re-asks.
    • unknown:[…] → template list is outdated; rerun TemplateList.
    • Any Apps Script error → the returned message is shown verbatim in chat.

3 — 🚀 Setup Steps (Full Checklist)

> Goal: Get a flawless PDF on the first run. > > > Mentally tick the ☑️ in front of every line as you go. >

☁️ A. Google Drive Preparation

| Step | Do This | Watch Out For | | --- | --- | --- | | 1 | Create a Templates/ folder → put every template Doc inside | Exactly one folder; no sub-folders | | 2 | Placeholders in every Doc are {{UPPER_CASE}} | No Turkish chars or spaces | | 3 | Wrap optional clauses with [[BLOCK_NAME:START]]…[[BLOCK_NAME:END]] | The START tag must have a blank line above | | 4 | Add a META_JSON block at the very end | Script deletes it automatically after fill | | 5 | Right-click Doc > Details ▸ Description = 1-line human description | Shown by the bot in the list | | 6 | Create a second Generated/ folder (for copies) | Keeps Drive tidy |

> 🔑 Folder ID (long alphanumerical) = <TEMPLATE_PARENT_ID> > > > We’ll paste this into the TemplateList node next. >

Simple sample template → Template Link


🛠 B. Import the Workflow into n8n

Settings ▸ Import Workflow ▸ DocAgent.json

If nodes look Broken afterwards → no community-node problem; you only need to select credentials.


📑 C. Customize the TemplateList Node

  1. Open Template List node ⚙️ → replace

    '%3CYOUR_PARENT_ID%3E' in parents

    with the real folder ID in the URL.

  2. Right-click node > Execute Node.

  3. Copy the entire JSON response.

  4. In the editor paste it into:

    • DocAgentSystem Prompt (top)

    • User Choice Match CheckSystem Prompt (top)

      Save.

> ⚠️ Why manual? Caching the list saves LLM tokens. Whenever you add a template, rerun the node and update the prompts. >


🔗 D. Deploy the Apps Script

| Step | Screen | Note | | --- | --- | --- | | 1 | Open Gist files GetMetaData.gs + FillDocument.gsFile ▸ Make a copy | Both files may live in one project | | 2 | Project Settings > enable Google Docs API ✔️ & Google Drive API ✔️ | Otherwise you’ll see 403 errors | | 3 | Deploy ▸ New deployment ▸ Web app | | | • Execute as | Me | | | • Who has access | Anyone | | | 4 | On the consent screen allow scopes:• …/auth/documents…/auth/drive | Click Advanced › Go if Google warns | | 5 | Copy the Web App URL (e.g. https://script.google.com/macros/s/ABC123/exec) | If this URL changes, update n8n |

Apps Script source code → Notion Link


🔧 E. Wire the Script URL in n8n

| Node | Field | Action | | --- | --- | --- | | GetMetaData | URL | &lt;WEB_APP_URL&gt;?mode=meta&id={{ $json["id"] }} | | FillDocument | URL | &lt;WEB_APP_URL&gt; |

> 💡 Prefer using an .env file? Add GAS_WEBAPP_URL=… and reference it as {{ $env.GAS_WEBAPP_URL }}. >


🔐 F. Add Credentials

  • Google Drive OAuth2Drive API (v3) Full Access
  • Google Docs OAuth2 → same account
  • LLM key (OpenAI / Gemini)
  • (Optional) Postgres Chat Memory credential for the corresponding node

🧪 G. First Run (Smoke Test)

  1. Switch the workflow Active.
  2. In the chat panel type /start.
  3. Bot lists templates → pick one.
  4. Fill mandatory fields, optionally toggle blocks → Confirm.
  5. 🔗 Download PDF link appears → ☑️ setup complete.

❌ H. Common Errors & Fixes

| 🆘 Error | Likely Cause | Remedy | | --- | --- | --- | | 403: Apps Script permission denied | Web app access set to User | Redeploy as Anyone, re-authorize scopes | | placeholder validation failed | Missing required field | Provide the listed values → rerun DocProcess | | unknown placeholders: … | Template vs. agent mismatch | Check placeholder spelling (UPPER_CASE ASCII) | | Template ID not found | Prompt list is old | Rerun TemplateList → update both prompts | | Cannot find META_JSON | No meta block / wrong tag | Add [[META_JSON_START]] … [[META_JSON_END]], retry |


✅ Final Checklist

  • [ ] Drive folder structure & template rules ready
  • [ ] Workflow imported, folder ID set in node
  • [ ] TemplateList output pasted into both prompts
  • [ ] Apps Script deployed, URL set in nodes
  • [ ] OAuth credentials & LLM key configured
  • [ ] /start test passes, PDF link received

🙋‍♂️ Need Help with Customizations?

Reach out for consulting & support on LinkedIn: Özgür Karateke

Full Documentation → Notion

Simple sample template → Template Link

Apps Script source code → Notion Link

Create Custom PDF Documents from Templates with Gemini & Google Drive

This n8n workflow leverages the power of Google Gemini (via LangChain integration) and Google Drive to automate the creation of custom PDF documents from templates. It allows you to dynamically generate personalized documents based on a prompt, store them in Google Drive, and even manage conversational context using a PostgreSQL database.

What it does

This workflow simplifies the process of generating dynamic documents by:

  1. Receiving Chat Messages: It starts by listening for incoming chat messages, acting as the trigger for the document generation process.
  2. Initializing Chat Memory: It sets up a PostgreSQL Chat Memory to maintain conversational context, allowing for multi-turn interactions.
  3. Defining an AI Agent: An AI Agent (Google Gemini Chat Model) is configured to understand the user's request and determine the necessary actions.
  4. Providing a "Create Document" Tool: A "Call n8n Workflow Tool" is defined, which, when invoked by the AI Agent, triggers a sub-workflow responsible for the actual document creation.
  5. Parsing AI Output: A Structured Output Parser extracts relevant data from the AI Agent's response for further processing.
  6. Calling the Document Creation Sub-workflow:
    • The sub-workflow is triggered by an "Execute Workflow Trigger" node.
    • It uses an "Edit Fields (Set)" node to prepare the data for the document template.
    • It makes an "HTTP Request" to a document generation service (e.g., a custom API or another n8n workflow that handles PDF generation).
    • It conditionally saves the generated document to Google Drive based on the success of the HTTP request.
    • A "Switch" node handles different outcomes of the document generation.

Prerequisites/Requirements

To use this workflow, you will need:

  • n8n Instance: A running n8n instance.
  • Google Gemini API Key: For the "Google Gemini Chat Model" node.
  • Google Drive Account: Configured as a credential in n8n for the "Google Drive" node.
  • PostgreSQL Database: For the "Postgres Chat Memory" node to store conversational history.
  • Document Generation Service/API: An endpoint that can take data and generate a PDF document (e.g., a custom service, a dedicated PDF generation API, or another n8n workflow). The "HTTP Request" node in the sub-workflow will call this service.
  • Sub-workflow for Document Creation: This workflow calls another n8n workflow (referred to as a tool) for the actual document creation. You will need to create and configure this sub-workflow separately, ensuring it has an "Execute Workflow Trigger" and handles the document generation logic.

Setup/Usage

  1. Import the Workflow: Download the provided JSON and import it into your n8n instance.
  2. Configure Credentials:
    • Set up your Google Gemini API Key credential for the "Google Gemini Chat Model" node.
    • Configure your Google Drive credential for the "Google Drive" node.
    • Set up your PostgreSQL credential for the "Postgres Chat Memory" node.
  3. Configure the "Call n8n Workflow Tool":
    • In the "Call n8n Workflow Tool" node, specify the Workflow ID of your sub-workflow that handles document creation. This sub-workflow should start with an "Execute Workflow Trigger" node.
  4. Configure the "HTTP Request" Node (in the sub-workflow):
    • Update the URL and body of the "HTTP Request" node in your document creation sub-workflow to point to your document generation service and pass the necessary data.
  5. Activate the Workflow: Once configured, activate the main workflow to start listening for chat messages.
  6. Interact via Chat: Send a chat message to the configured "Chat Trigger" endpoint (e.g., via a messaging platform integrated with n8n) with a request like "create a document for [details]". The AI Agent will interpret your request and use the "Create Document" tool to generate and store the PDF.

Related Templates

Track competitor SEO keywords with Decodo + GPT-4.1-mini + Google Sheets

This workflow automates competitor keyword research using OpenAI LLM and Decodo for intelligent web scraping. Who this is for SEO specialists, content strategists, and growth marketers who want to automate keyword research and competitive intelligence. Marketing analysts managing multiple clients or websites who need consistent SEO tracking without manual data pulls. Agencies or automation engineers using Google Sheets as an SEO data dashboard for keyword monitoring and reporting. What problem this workflow solves Tracking competitor keywords manually is slow and inconsistent. Most SEO tools provide limited API access or lack contextual keyword analysis. This workflow solves that by: Automatically scraping any competitor’s webpage with Decodo. Using OpenAI GPT-4.1-mini to interpret keyword intent, density, and semantic focus. Storing structured keyword insights directly in Google Sheets for ongoing tracking and trend analysis. What this workflow does Trigger — Manually start the workflow or schedule it to run periodically. Input Setup — Define the website URL and target country (e.g., https://dev.to, france). Data Scraping (Decodo) — Fetch competitor web content and metadata. Keyword Analysis (OpenAI GPT-4.1-mini) Extract primary and secondary keywords. Identify focus topics and semantic entities. Generate a keyword density summary and SEO strength score. Recommend optimization and internal linking opportunities. Data Structuring — Clean and convert GPT output into JSON format. Data Storage (Google Sheets) — Append structured keyword data to a Google Sheet for long-term tracking. Setup Prerequisites If you are new to Decode, please signup on this link visit.decodo.com n8n account with workflow editor access Decodo API credentials OpenAI API key Google Sheets account connected via OAuth2 Make sure to install the Decodo Community node. Create a Google Sheet Add columns for: primarykeywords, seostrengthscore, keyworddensity_summary, etc. Share with your n8n Google account. Connect Credentials Add credentials for: Decodo API credentials - You need to register, login and obtain the Basic Authentication Token via Decodo Dashboard OpenAI API (for GPT-4o-mini) Google Sheets OAuth2 Configure Input Fields Edit the “Set Input Fields” node to set your target site and region. Run the Workflow Click Execute Workflow in n8n. View structured results in your connected Google Sheet. How to customize this workflow Track Multiple Competitors → Use a Google Sheet or CSV list of URLs; loop through them using the Split In Batches node. Add Language Detection → Add a Gemini or GPT node before keyword analysis to detect content language and adjust prompts. Enhance the SEO Report → Expand the GPT prompt to include backlink insights, metadata optimization, or readability checks. Integrate Visualization → Connect your Google Sheet to Looker Studio for SEO performance dashboards. Schedule Auto-Runs → Use the Cron Node to run weekly or monthly for competitor keyword refreshes. Summary This workflow automates competitor keyword research using: Decodo for intelligent web scraping OpenAI GPT-4.1-mini for keyword and SEO analysis Google Sheets for live tracking and reporting It’s a complete AI-powered SEO intelligence pipeline ideal for teams that want actionable insights on keyword gaps, optimization opportunities, and content focus trends, without relying on expensive SEO SaaS tools.

Ranjan DailataBy Ranjan Dailata
161

Generate song lyrics and music from text prompts using OpenAI and Fal.ai Minimax

Spark your creativity instantly in any chat—turn a simple prompt like "heartbreak ballad" into original, full-length lyrics and a professional AI-generated music track, all without leaving your conversation. 📋 What This Template Does This chat-triggered workflow harnesses AI to generate detailed, genre-matched song lyrics (at least 600 characters) from user messages, then queues them for music synthesis via Fal.ai's minimax-music model. It polls asynchronously until the track is ready, delivering lyrics and audio URL back in chat. Crafts original, structured lyrics with verses, choruses, and bridges using OpenAI Submits to Fal.ai for melody, instrumentation, and vocals aligned to the style Handles long-running generations with smart looping and status checks Returns complete song package (lyrics + audio link) for seamless sharing 🔧 Prerequisites n8n account (self-hosted or cloud with chat integration enabled) OpenAI account with API access for GPT models Fal.ai account for AI music generation 🔑 Required Credentials OpenAI API Setup Go to platform.openai.com → API keys (sidebar) Click "Create new secret key" → Name it (e.g., "n8n Songwriter") Copy the key and add to n8n as "OpenAI API" credential type Test by sending a simple chat completion request Fal.ai HTTP Header Auth Setup Sign up at fal.ai → Dashboard → API Keys Generate a new API key → Copy it In n8n, create "HTTP Header Auth" credential: Name="Fal.ai", Header Name="Authorization", Header Value="Key [Your API Key]" Test with a simple GET to their queue endpoint (e.g., /status) ⚙️ Configuration Steps Import the workflow JSON into your n8n instance Assign OpenAI API credentials to the "OpenAI Chat Model" node Assign Fal.ai HTTP Header Auth to the "Generate Music Track", "Check Generation Status", and "Fetch Final Result" nodes Activate the workflow—chat trigger will appear in your n8n chat interface Test by messaging: "Create an upbeat pop song about road trips" 🎯 Use Cases Content Creators: YouTubers generating custom jingles for videos on the fly, streamlining production from idea to audio export Educators: Music teachers using chat prompts to create era-specific folk tunes for classroom discussions, fostering interactive learning Gift Personalization: Friends crafting anniversary R&B tracks from shared memories via quick chats, delivering emotional audio surprises Artist Brainstorming: Songwriters prototyping hip-hop beats in real-time during sessions, accelerating collaboration and iteration ⚠️ Troubleshooting Invalid JSON from AI Agent: Ensure the system prompt stresses valid JSON; test the agent standalone with a sample query Music Generation Fails (401/403): Verify Fal.ai API key has minimax-music access; check usage quotas in dashboard Status Polling Loops Indefinitely: Bump wait time to 45-60s for complex tracks; inspect fal.ai queue logs for bottlenecks Lyrics Under 600 Characters: Tweak agent prompt to enforce fuller structures like [V1][C][V2][B][C]; verify output length in executions

Daniel NkenchoBy Daniel Nkencho
601

Auto-reply & create Linear tickets from Gmail with GPT-5, gotoHuman & human review

This workflow automatically classifies every new email from your linked mailbox, drafts a personalized reply, and creates Linear tickets for bugs or feature requests. It uses a human-in-the-loop with gotoHuman and continuously improves itself by learning from approved examples. How it works The workflow triggers on every new email from your linked mailbox. Self-learning Email Classifier: an AI model categorizes the email into defined categories (e.g., Bug Report, Feature Request, Sales Opportunity, etc.). It fetches previously approved classification examples from gotoHuman to refine decisions. Self-learning Email Writer: the AI drafts a reply to the email. It learns over time by using previously approved replies from gotoHuman, with per-classification context to tailor tone and style (e.g., different style for sales vs. bug reports). Human Review in gotoHuman: review the classification and the drafted reply. Drafts can be edited or retried. Approved values are used to train the self-learning agents. Send approved Reply: the approved response is sent as a reply to the email thread. Create ticket: if the classification is Bug or Feature Request, a ticket is created by another AI agent in Linear. Human Review in gotoHuman: How to set up Most importantly, install the gotoHuman node before importing this template! (Just add the node to a blank canvas before importing) Set up credentials for gotoHuman, OpenAI, your email provider (e.g. Gmail), and Linear. In gotoHuman, select and create the pre-built review template "Support email agent" or import the ID: 6fzuCJlFYJtlu9mGYcVT. Select this template in the gotoHuman node. In the "gotoHuman: Fetch approved examples" http nodes you need to add your formId. It is the ID of the review template that you just created/imported in gotoHuman. Requirements gotoHuman (human supervision, memory for self-learning) OpenAI (classification, drafting) Gmail or your preferred email provider (for email trigger+replies) Linear (ticketing) How to customize Expand or refine the categories used by the classifier. Update the prompt to reflect your own taxonomy. Filter fetched training data from gotoHuman by reviewer so the writer adapts to their personalized tone and preferences. Add more context to the AI email writer (calendar events, FAQs, product docs) to improve reply quality.

gotoHumanBy gotoHuman
353