N8N Integration Guide
N8N Integration Guide
Automate document generation workflows using n8n, the powerful workflow automation platform.
Table of Contents
Overview
The DataMagik n8n node allows you to:
- Generate documents from templates
- List available templates
- Integrate document generation into complex workflows
- Automate document creation based on triggers (webhooks, schedules, events)
- Process batch document generation
- Send generated documents via email, store in cloud, or trigger other actions
Key Features
- ✅ Auto-completion: Automatically waits for document generation
- ✅ Binary download: Optionally returns document as binary data
- ✅ Status polling: Built-in polling for queued requests
- ✅ Error handling: Comprehensive error management
- ✅ Priority support: Set generation priority
- ✅ Template browsing: List and search templates
Installation
From n8n Community Nodes
- Open n8n interface
- Go to Settings → Community Nodes
- Click Install
- Enter:
n8n-nodes-datamagik-docs
- Click Install
- Restart n8n
Manual Installation
cd ~/.n8n/custom npm install n8n-nodes-datamagik-docs # Restart n8n
Using Docker
FROM n8nio/n8n:latest USER root RUN cd /usr/local/lib/node_modules/n8n && \ npm install n8n-nodes-datamagik-docs USER node
Configuration
Add Credentials
- Go to Credentials in n8n
- Click New Credential
- Search for "DataMagik Document Generation API"
- Enter your credentials:
Fields:
- API URL: Your DataMagik instance URL (e.g.,
https://data-magik.com
) - API Key: Your API key (from DataMagik settings)
OR
- JWT Token: Your authentication token
Example:
API URL: https://data-magik.com API Key: dmk_abc123def456ghi789
N8N Node Operations
Generate Document
Creates a document from a template. Automatically waits for completion (up to 2 minutes).
Required Parameters
- Template ID: The ID of the template (always provide as string)
- Format: PDF or HTML
- Return Type: URL or Binary
- Template Data: JSON object with data to populate the template
Optional Parameters
- Priority: Queue priority (Urgent, High, Normal, Low)
- Custom Filename: Custom name for the generated file
- Template Branch: Template branch to use (default: main)
- Template Version: Specific template version
- Force Regenerate: Force regeneration even if cached
- Document Settings: Page size, orientation, margins, etc.
Example Configuration
{ "operation": "generate", "templateId": "1097823044285431810", "format": "pdf", "returnType": "url", "templateData": { "customer_name": "{{ $json.customer_name }}", "invoice_number": "{{ $json.invoice_number }}", "amount": "{{ $json.total_amount }}" }, "priority": "normal", "documentSettings": { "page_size": "A4", "orientation": "portrait", "margin_top": 1.0, "margin_right": 1.0, "margin_bottom": 1.0, "margin_left": 1.0, "show_page_number": true, "show_timestamp": true, "print_background": true, "ttlOptionId": 3 } }
Output
URL Return Type:
{ "success": true, "document_id": 456, "download_url": "https://s3.amazonaws.com/bucket/documents/abc123.pdf", "filename": "document_2025_001.pdf", "format": "pdf", "status": "completed" }
Binary Return Type: Returns the document as binary data that can be used in subsequent nodes (e.g., Send Email node).
List Templates
Gets all available templates for searching and selection.
Optional Parameters
- Search Query: Filter templates by name/description
- Include Deleted: Include deleted templates
- Page: Page number for pagination
- Size: Results per page (max 100)
Example Configuration
{ "operation": "listTemplates", "searchQuery": "invoice", "includeDeleted": "false", "page": 1, "size": 25 }
Output
{ "items": [ { "templateId": "123", "name": "Invoice Template", "description": "Standard invoice template", "category": "Invoices", "isActive": true } ], "page": 1, "size": 25 }
Workflow Examples
Example 1: Invoice Generation on New Order
Trigger: Webhook receives new order Action: Generate and email invoice PDF
{ "name": "Order to Invoice", "nodes": [ { "name": "Webhook", "type": "n8n-nodes-base.webhook", "parameters": { "path": "new-order", "responseMode": "onReceived", "httpMethod": "POST" } }, { "name": "Generate Invoice", "type": "n8n-nodes-datamagik.documentGeneration", "parameters": { "operation": "generate", "templateId": "1097823044285431810", "format": "pdf", "returnType": "binary", "templateData": { "invoice_number": "{{ $json.body.order_id }}", "customer_name": "{{ $json.body.customer.name }}", "customer_email": "{{ $json.body.customer.email }}", "items": "{{ $json.body.items }}", "subtotal": "{{ $json.body.subtotal }}", "tax": "{{ $json.body.tax }}", "total": "{{ $json.body.total }}", "invoice_date": "{{ $now.format('YYYY-MM-DD') }}" }, "priority": "high", "fileName": "Invoice_{{ $json.body.order_id }}" } }, { "name": "Send Email", "type": "n8n-nodes-base.emailSend", "parameters": { "toEmail": "={{ $node['Webhook'].json.body.customer.email }}", "subject": "Your Invoice #{{ $node['Webhook'].json.body.order_id }}", "text": "Thank you for your order. Please find your invoice attached.", "attachments": "data" } } ], "connections": { "Webhook": { "main": [[{ "node": "Generate Invoice", "type": "main", "index": 0 }]] }, "Generate Invoice": { "main": [[{ "node": "Send Email", "type": "main", "index": 0 }]] } } }
Example 2: Scheduled Monthly Reports
Trigger: Cron schedule (first day of month) Action: Generate reports for all customers
{ "name": "Monthly Reports", "nodes": [ { "name": "Schedule Trigger", "type": "n8n-nodes-base.cron", "parameters": { "triggerTimes": { "item": [ { "mode": "everyMonth", "dayOfMonth": 1, "hour": 8, "minute": 0 } ] } } }, { "name": "Get Customers", "type": "n8n-nodes-base.httpRequest", "parameters": { "url": "https://your-api.com/customers", "method": "GET", "authentication": "genericCredentialType", "responseFormat": "json" } }, { "name": "Get Customer Data", "type": "n8n-nodes-base.httpRequest", "parameters": { "url": "https://your-api.com/customers/{{ $json.id }}/monthly-data", "method": "GET", "responseFormat": "json" } }, { "name": "Generate Report", "type": "n8n-nodes-datamagik.documentGeneration", "parameters": { "operation": "generate", "templateId": "monthly_report_template_id", "format": "pdf", "returnType": "url", "templateData": { "customer_name": "={{ $json.name }}", "report_month": "={{ $now.minus({ months: 1 }).format('MMMM YYYY') }}", "total_revenue": "={{ $json.revenue }}", "orders_count": "={{ $json.orders_count }}", "top_products": "={{ $json.top_products }}" }, "priority": "low", "fileName": "Report_{{ $json.id }}_{{ $now.format('YYYY_MM') }}" } }, { "name": "Send Report", "type": "n8n-nodes-base.emailSend", "parameters": { "toEmail": "={{ $node['Get Customer Data'].json.email }}", "subject": "Your Monthly Report - {{ $now.minus({ months: 1 }).format('MMMM YYYY') }}", "text": "Please find your monthly report attached.", "attachments": "={{ $node['Generate Report'].json.download_url }}" } } ] }
Example 3: Bulk Certificate Generation
Trigger: Manual trigger or CSV upload Action: Generate certificates for all attendees
{ "name": "Bulk Certificates", "nodes": [ { "name": "Manual Trigger", "type": "n8n-nodes-base.manualTrigger" }, { "name": "Read CSV", "type": "n8n-nodes-base.readBinaryFile", "parameters": { "filePath": "/path/to/attendees.csv", "dataPropertyName": "data" } }, { "name": "Parse CSV", "type": "n8n-nodes-base.spreadsheetFile", "parameters": { "operation": "read", "binaryPropertyName": "data" } }, { "name": "Generate Certificate", "type": "n8n-nodes-datamagik.documentGeneration", "parameters": { "operation": "generate", "templateId": "certificate_template_id", "format": "pdf", "returnType": "binary", "templateData": { "attendee_name": "={{ $json.name }}", "course_name": "={{ $json.course }}", "completion_date": "={{ $json.date }}", "certificate_id": "CERT-{{ $json.id }}" }, "priority": "low", "fileName": "Certificate_{{ $json.name.replace(' ', '_') }}" } }, { "name": "Save to Dropbox", "type": "n8n-nodes-base.dropbox", "parameters": { "operation": "upload", "path": "/certificates/{{ $json.fileName }}.pdf", "binaryData": true, "binaryPropertyName": "data" } }, { "name": "Send Notification", "type": "n8n-nodes-base.emailSend", "parameters": { "toEmail": "={{ $node['Parse CSV'].json.email }}", "subject": "Your Course Completion Certificate", "text": "Congratulations! Your certificate is ready.", "attachments": "data" } } ] }
Example 4: CRM Integration - Quote Generation
Trigger: CRM opportunity stage change Action: Generate and attach quote document
{ "name": "CRM Quote Generation", "nodes": [ { "name": "CRM Webhook", "type": "n8n-nodes-base.webhook", "parameters": { "path": "crm-opportunity-updated", "httpMethod": "POST" } }, { "name": "Check Stage", "type": "n8n-nodes-base.if", "parameters": { "conditions": { "string": [ { "value1": "={{ $json.body.stage }}", "operation": "equals", "value2": "quote_requested" } ] } } }, { "name": "Get Opportunity Details", "type": "n8n-nodes-base.httpRequest", "parameters": { "url": "https://crm-api.com/opportunities/{{ $json.body.opportunity_id }}", "method": "GET" } }, { "name": "Generate Quote", "type": "n8n-nodes-datamagik.documentGeneration", "parameters": { "operation": "generate", "templateId": "quote_template_id", "format": "pdf", "returnType": "url", "templateData": { "quote_number": "Q-{{ $json.id }}", "company_name": "={{ $json.account.name }}", "contact_name": "={{ $json.contact.name }}", "products": "={{ $json.products }}", "subtotal": "={{ $json.subtotal }}", "discount": "={{ $json.discount }}", "tax": "={{ $json.tax }}", "total": "={{ $json.total }}", "valid_until": "={{ $now.plus({ days: 30 }).format('YYYY-MM-DD') }}" }, "priority": "high" } }, { "name": "Update CRM", "type": "n8n-nodes-base.httpRequest", "parameters": { "url": "https://crm-api.com/opportunities/{{ $node['CRM Webhook'].json.body.opportunity_id }}/attach-document", "method": "POST", "bodyParameters": { "parameters": [ { "name": "document_url", "value": "={{ $node['Generate Quote'].json.download_url }}" }, { "name": "document_type", "value": "quote" } ] } } }, { "name": "Notify Sales Rep", "type": "n8n-nodes-base.slack", "parameters": { "channel": "#sales", "text": "Quote generated for {{ $node['Get Opportunity Details'].json.account.name }}", "attachments": [ { "text": "View quote: {{ $node['Generate Quote'].json.download_url }}" } ] } } ] }
Best Practices
1. Use String Template IDs
Always pass template IDs as strings to avoid precision issues:
{ "templateId": "1097823044285431810" // ✅ Correct }
NOT:
{ "templateId": 1097823044285431810 // ❌ May lose precision }
2. Handle Errors Gracefully
Add error handling nodes:
{ "name": "On Error", "type": "n8n-nodes-base.noOp", "parameters": {}, "onError": "continueRegularOutput" }
3. Set Appropriate Priority
- Urgent: User is waiting for document
- High: Time-sensitive documents
- Normal: Standard generation (default)
- Low: Bulk operations, reports
4. Use Binary for Email Attachments
When sending documents via email, use returnType: "binary"
:
{ "returnType": "binary" }
5. Batch Processing
For bulk operations, use lower priority and add delays:
// In Code node before generation await new Promise(resolve => setTimeout(resolve, 1000)); // 1 second delay
6. Monitor Quota Usage
Add quota check before bulk operations:
{ "name": "Check Quota", "type": "n8n-nodes-base.httpRequest", "parameters": { "url": "https://data-magik.com/api/quota/status", "method": "GET" } }
7. Cache Template Responses
Store frequently used template data to reduce API calls:
{ "name": "Cache Templates", "type": "n8n-nodes-base.set", "parameters": { "mode": "manual", "duplicateItem": false, "values": { "string": [ { "name": "template_id", "value": "={{ $json.templateId }}" } ] } } }
Troubleshooting
Document Generation Fails
Problem: Node returns error about template not found
Solutions:
- Verify template ID is correct
- Ensure template exists and is active
- Check authentication credentials
- Verify company has access to template
Timeout Errors
Problem: Generation times out
Solutions:
- Check document complexity
- Verify template renders correctly
- Increase timeout in node settings
- Use lower priority for large documents
Binary Data Issues
Problem: Binary download doesn't work with email node
Solutions:
- Ensure returnType is "binary"
- Check binary property name matches
- Verify email node configuration
- Test with simpler document first
Webhook Not Triggering
Problem: N8N workflow doesn't start from webhook
Solutions:
- Verify webhook URL is correct
- Check webhook is active
- Test with curl or Postman
- Review n8n logs for errors
Data Mapping Issues
Problem: Template data not populating correctly
Solutions:
- Use expression editor to test data paths
- Check JSON structure matches template expectations
- Use Set node to transform data first
- Review template sample data requirements
Integration Patterns
Pattern 1: Fire-and-Forget
Generate document and don't wait for result:
{ "priority": "low", "returnType": "url" // Don't add nodes after this }
Pattern 2: Wait and Process
Generate document and use result immediately:
{ "priority": "urgent", "returnType": "binary" // Add email/storage nodes after }
Pattern 3: Batch with Retry
Process multiple documents with error handling:
// Add loop, delay, and retry logic
Pattern 4: Conditional Generation
Generate different documents based on conditions:
// Use IF node to route to different templates
Next Steps
- Review API Reference for detailed API documentation
- Learn about Automation Setup for platform automations
- Check Starter Templates for template examples
Need Help? Check the n8n community forums or DataMagik support for integration assistance.