Generating PDFs in n8n Using Google Docs: Tutorial with JSON Code for Import

I was working on a Telegram bot that generates a document for the user and sends it via chat. I had a PDF template where I needed to insert values dynamically and generate the file on the fly. To achieve this, I used Google Docs and exported the document as a PDF. Here’s a step-by-step guide on how to do it.

Overview of the Workflow

The process involves the following steps:

  1. Create a document template in Google Docs.
  2. Add a service account to the document (details below).
  3. In your n8n workflow, copy this document into a new file.
  4. Use the document modification node to replace placeholders (for example, {client_name} with the actual client’s name).
  5. Convert the final document into a PDF and proceed with further workflow steps as needed.

This method allows you to dynamically generate personalized PDFs based on a predefined template.

This post is sponsored by n8ndevs.com

n8ndevs.com is a platform where companies connect with n8n developers and experts. If you’re a developer, join n8ndevs to find opportunities. If you need a full-time or part-time developer for automation, find the right specialist on n8ndevs.com.

Creating a Service Account and Assigning Permissions

To work with Google Docs and Google Drive in n8n, you need to set up a service account. n8n provides a detailed guide for this: n8n Service Account Setup. Follow these steps to create a service account.

Two critical steps to keep in mind:

  • Enable Google Drive API.
  • Enable Google Docs API.

These steps are outlined in the Enable APIs section of the n8n documentation. If these APIs are not enabled, your workflow will fail.

Once this setup is complete, you will receive a service account email like this:

[email protected]

You will need this email in the next step.

Creating the Document Template

  1. Open Google Docs and create a new document.
  2. Structure the document according to your needs (for example, import an existing MS Word document).
  3. Insert placeholders in the format {variable_name} or %variable_name%—choose whichever is more convenient for you.
  4. Share the document with your service account by granting editor access.

This template will be used as the base file for dynamically generating documents.

Setting Up the n8n Workflow

Step 1: Copying the Template

  1. Add a Google Drive node.
  2. Select FileCopy.
  3. Specify your template file.

This will create a new copy of the document to work with. The result of this step will look like this:

Step 2: Replacing Placeholders

  1. Add a Google Docs node.
  2. Choose the Update operation.
  3. In Doc ID, specify the ID of the copied document.
  4. Under Actions, select Find and Replace and map the placeholders to the actual values.

For example, replacing {client_name} with “John Doe”. Here are node settings from my example:

Step 3: Exporting as a PDF

  1. Add a Google Drive node.
  2. Choose FileDownload.
  3. Select Google Docs export to PDF and specify the filename.

This final step converts the document into a PDF file that can be sent or stored as needed. Here are node settings:

Full Code to import for your workflow

{
  "name": "Temp for tests",
  "nodes": [
    {
      "parameters": {
        "authentication": "serviceAccount",
        "operation": "update",
        "documentURL": "={{ $json.id }}",
        "actionsUi": {
          "actionFields": [
            {
              "action": "replaceAll",
              "text": "{contract_number}",
              "replaceText": "={{ $('Parallel_GenerateStep').item.json.currentContract.contract_code }}"
            },
            {
              "action": "replaceAll",
              "text": "{contract_date}",
              "replaceText": "={{ new Date($('Parallel_GenerateStep').item.json.currentContract.contract_date).toLocaleDateString('en-US', { day: 'numeric', month: 'long', year: 'numeric' }) }}"
            },
          ]
        }
      },
      "type": "n8n-nodes-base.googleDocs",
      "typeVersion": 2,
      "position": [
        220,
        200
      ],
      "id": "69f15ad1-23da-4f05-8f2b-e7eddcd93800",
      "name": "ReplaceVariables",
      "credentials": {
        "googleApi": {
          "id": "ECGXYcUZP4YMCmGE",
          "name": "AdHelper: Google Docs"
        }
      }
    },
    {
      "parameters": {
        "authentication": "serviceAccount",
        "operation": "download",
        "fileId": {
          "__rl": true,
          "value": "={{ $json.documentId }}",
          "mode": "id"
        },
        "options": {
          "binaryPropertyName": "data",
          "googleFileConversion": {
            "conversion": {
              "docsToFormat": "application/pdf"
            }
          },
          "fileName": "Contract-abcd.pdf"
        }
      },
      "type": "n8n-nodes-base.googleDrive",
      "typeVersion": 3,
      "position": [
        420,
        200
      ],
      "id": "7d9ed93e-2549-4900-aeaf-2c4ae787b913",
      "name": "GeneratePDF",
      "credentials": {
        "googleApi": {
          "id": "ECGXYcUZP4YMCmGE",
          "name": "AdHelper: Google Docs"
        }
      }
    },
    {
      "parameters": {},
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        -200,
        200
      ],
      "id": "e26cecb0-b6bd-4155-9f9c-44d20a67068c",
      "name": "When clicking ‘Test workflow’"
    },
    {
      "parameters": {
        "authentication": "serviceAccount",
        "operation": "copy",
        "fileId": {
          "__rl": true,
          "value": "1MQ0-_9r0sM7toyuTNNx6yq-nc0-NQcSoWqhNKACJ7gA",
          "mode": "list",
          "cachedResultName": "",
          "cachedResultUrl": ""
        },
        "name": "=Contract_{{ $json.currentUser.telegram_id }}_100",
        "options": {}
      },
      "type": "n8n-nodes-base.googleDrive",
      "typeVersion": 3,
      "position": [
        20,
        200
      ],
      "id": "2da0e829-2055-4ba9-87ce-271a65eb579b",
      "name": "CreateContractFile",
      "alwaysOutputData": true,
      "credentials": {
        "googleApi": {
          "id": "ECGXYcUZP4YMCmGE",
          "name": "AdHelper: Google Docs"
        }
      }
    }
  ],
  "pinData": {},
  "connections": {
    "ReplaceVariables": {
      "main": [
        [
          {
            "node": "GeneratePDF",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "When clicking ‘Test workflow’": {
      "main": [
        [
          {
            "node": "CreateContractFile",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "CreateContractFile": {
      "main": [
        [
          {
            "node": "ReplaceVariables",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "4b164c45-ec59-4d3f-b8fd-7c46d4311fd5",
  "meta": {
    "instanceId": "328c1bd4ecd21bbf0ba88baaaf1c128b060d87150756887eaf31d6fefcee518a"
  },
  "id": "k7zkyfYMbX4fCBT7",
  "tags": []
}

Use Cases

This method is useful in various scenarios, such as:

  • Invoice generation: Dynamically create invoices with customer details.
  • Contracts and agreements: Automate document generation for legal or business agreements.
  • Certificates and reports: Personalize and generate PDF reports or certificates for users.

Conclusion

With this simple yet effective approach, you can create an automated PDF generator in n8n using Google Docs as a template engine. This eliminates the need for external PDF generation tools while keeping everything within a seamless workflow.

By leveraging Google Docs’ built-in capabilities, you can create customized documents quickly and efficiently. Let me know if you have any questions or need further assistance!

For YouTubers & Video Tutorials

If you run a YouTube channel and create videos about n8n, and you’d like to cover this post and the PDF solution—please include a link to this post in your video description. This will help promote our platform.

Leave a Reply

Your email address will not be published. Required fields are marked *