Blog

PDF Generation with n8n: Complete Guide to Automated Document Creation

Automating PDF generation in n8n workflows transforms how businesses handle invoices, reports, and documents. Instead of manually creating PDFs or relying on expensive third-party services, n8n enables automated PDF creation directly within your workflow automation platform.

The demand for automated document generation continues to grow. 98% of companies use PDFs as their default format for external communication, making PDF automation essential for modern business operations. Whether you're generating invoices from Airtable, creating reports from database queries, or producing certificates from form submissions, n8n provides the infrastructure to automate these processes.

This comprehensive guide covers everything you need to know about PDF generation in n8n, from basic HTML to PDF conversion to advanced invoice generation with dynamic data. We'll explore the CustomJS nodes that make PDF automation possible, share real-world workflow templates, and provide best practices for implementing automated document generation at scale.

TL;DR

  • n8n PDF generation enables automated document creation directly within workflows using CustomJS nodes.
  • Two primary methods: HTML to PDF conversion for custom designs and Invoice Generator for pre-built templates.
  • CustomJS offers 600 free PDF generations per month, making it cost-effective for small to medium workflows.
  • Native n8n integration eliminates the need for external API calls or custom code.
  • Perfect for automating invoices, reports, certificates, and any document that requires consistent formatting.

🛠️ Complete PDF Toolkit for n8n

CustomJS provides a comprehensive suite of PDF tools for n8n workflows. Beyond basic PDF generation, you can:

HTML to PDF

Convert HTML to professional PDFs

Invoice Generator

Pre-built invoice templates

Merge PDFs

Combine multiple PDFs into one

Compress PDFs

Reduce PDF file sizes

Extract PDF Pages

Split PDFs by page range

PDF to PNG

Convert PDF pages to images

PDF to Text

Extract text from PDFs

Video Guide: PDF Generation in n8n

Why Use n8n for PDF Generation?

n8n is an open-source workflow automation platform that allows you to connect different services and automate repetitive tasks. When it comes to PDF generation, n8n offers several advantages over traditional methods:

Native Integration: Unlike external PDF APIs that require HTTP requests and authentication management, CustomJS nodes integrate directly into n8n workflows. This means no API keys to manage, no external dependencies, and no additional latency from external service calls.

Visual Workflow Design: n8n's visual interface makes it easy to see how data flows from your source (Airtable, databases, webhooks) through transformation steps and into PDF generation. This transparency helps with debugging and makes workflows maintainable by team members who aren't developers.

Cost-Effective Automation: With CustomJS's free tier of 600 PDFs per month and predictable pricing beyond that, n8n PDF generation is significantly cheaper than dedicated PDF services. For businesses generating hundreds of invoices or reports monthly, this can mean thousands of dollars in savings annually.

Flexible Data Sources: n8n connects to hundreds of services out of the box. You can pull data from Airtable, Google Sheets, PostgreSQL, REST APIs, or any other source, transform it as needed, and generate PDFs—all in one workflow without writing backend code.

Two Approaches to PDF Generation in n8n

CustomJS provides two specialized nodes for PDF generation in n8n, each designed for different use cases:

1. HTML to PDF Node

The HTML to PDF node converts any HTML content into a professionally formatted PDF. This approach gives you complete design control using HTML and CSS, making it ideal for:

  • Custom Reports: Create branded reports with charts, tables, and custom layouts that match your company's design system.
  • Certificates: Generate certificates with specific fonts, logos, and positioning requirements.
  • Marketing Materials: Produce brochures, flyers, or product sheets with precise design specifications.
  • Complex Documents: Build multi-page documents with headers, footers, page numbers, and custom styling.

The HTML to PDF node accepts raw HTML, allowing you to use modern CSS features like Flexbox and Grid for layout. You can inject dynamic data using n8n's expression syntax, making it easy to populate templates with information from previous workflow steps.

2. Invoice Generator Node

The Invoice Generator node provides a pre-built, professional invoice template that handles all the formatting for you. Instead of writing HTML and CSS, you simply provide structured data:

  • Issuer Information: Your company name, address, and contact details.
  • Recipient Details: Customer name, address, and billing information.
  • Line Items: Products or services with descriptions, quantities, prices, and totals.
  • Payment Terms: Due dates, payment methods, and banking information.

This approach is perfect for businesses that need to generate invoices quickly without worrying about design. The template is professionally designed, includes all standard invoice elements, and automatically calculates totals and taxes.

Ready-to-Use Workflow Templates

Get started immediately with these production-ready workflow templates. Import them directly into n8n and customize for your needs.

Template 1: Automatic Invoice Generation with Airtable

What it does:

  • Monitors Airtable for orders ready to be invoiced
  • Retrieves customer details and line items from related tables
  • Generates professional invoice PDF using Invoice Generator
  • Sends invoice via email with PDF attachment
  • Updates order status in Airtable to "Invoiced"
View Template →

Template 2: HTML to PDF via Webhook

What it does:

  • Accepts HTML content via POST request
  • Converts HTML to PDF using CustomJS PDF toolkit
  • Returns PDF directly to the webhook requester
  • Perfect for integrating with external applications
View Template →

Setting Up PDF Generation in n8n

Before you can generate PDFs in n8n, you need to install the CustomJS community package. This package adds the PDF generation nodes to your n8n instance.

Installation Requirements

CustomJS nodes are only available on the hosted n8n version (n8n.cloud). Self-hosted n8n instances don't support community packages due to security restrictions. If you're using self-hosted n8n, you'll need to use the CustomJS API directly via HTTP Request nodes.

Installing CustomJS Package

  1. Log in to your n8n.cloud account.
  2. Navigate to SettingsCommunity Nodes.
  3. Click Install a community node.
  4. Enter the package name: @customjs/n8n-nodes
  5. Click Install and wait for the installation to complete.
  6. Refresh your n8n interface to see the new nodes.

Once installed, you'll see two new nodes in your node palette: HTML to PDF (customJS) and Invoice Generator (customJS).

HTML to PDF: Complete Workflow Example

Let's build a complete workflow that generates a custom PDF report from data in Airtable. This example demonstrates how to fetch data, transform it, and create a professionally formatted PDF.

Workflow Structure

  1. Webhook Trigger: Receives a request to generate a report.
  2. Airtable Node: Fetches data from your Airtable base.
  3. Code Node: Transforms data into HTML format.
  4. HTML to PDF Node: Converts HTML to PDF.
  5. Email Node: Sends the PDF via email.

Step-by-Step Implementation

Step 1: Set Up the Webhook

Add a Webhook node and set it to POST method. This will be the entry point for your workflow. The webhook can receive parameters like report type, date range, or customer ID.

Step 2: Fetch Data from Airtable

Add an Airtable node and configure it to fetch records from your base. You can use filters to get specific records based on the webhook parameters:

// Filter formula in Airtable node
{Status} = 'Completed'

Step 3: Transform Data to HTML

Add a Code node to transform your Airtable data into HTML. Here's an example that creates a styled report:

const items = $input.all();

const html = `
<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      font-family: Arial, sans-serif;
      padding: 40px;
      color: #333;
    }
    h1 {
      color: #2563eb;
      border-bottom: 3px solid #2563eb;
      padding-bottom: 10px;
    }
    table {
      width: 100%;
      border-collapse: collapse;
      margin-top: 20px;
    }
    th {
      background-color: #2563eb;
      color: white;
      padding: 12px;
      text-align: left;
    }
    td {
      padding: 10px;
      border-bottom: 1px solid #ddd;
    }
    tr:hover {
      background-color: #f5f5f5;
    }
    .total {
      font-weight: bold;
      font-size: 18px;
      margin-top: 20px;
      text-align: right;
    }
  </style>
</head>
<body>
  <h1>Sales Report</h1>
  <p>Generated: ${new Date().toLocaleDateString()}</p>
  
  <table>
    <thead>
      <tr>
        <th>Product</th>
        <th>Quantity</th>
        <th>Price</th>
        <th>Total</th>
      </tr>
    </thead>
    <tbody>
      ${items.map(item => `
        <tr>
          <td>${item.json.Product}</td>
          <td>${item.json.Quantity}</td>
          <td>$${item.json.Price}</td>
          <td>$${item.json.Quantity * item.json.Price}</td>
        </tr>
      `).join('')}
    </tbody>
  </table>
  
  <div class="total">
    Total: $${items.reduce((sum, item) => 
      sum + (item.json.Quantity * item.json.Price), 0
    )}
  </div>
</body>
</html>
`;

return { json: { html } };

Step 4: Generate PDF

Add the HTML to PDF (customJS) node and configure it:

  • HTML Input: {{ $json.html }}
  • Output Format: Binary (for email attachments)
  • Page Options: Set margins, orientation, and page size as needed

Step 5: Send via Email

Add a Send Email node (Gmail, Outlook, or SMTP) and attach the PDF:

  • Attachment: Select the binary data from the HTML to PDF node
  • Filename: report-{{ $now.format('YYYY-MM-DD') }}.pdf

Invoice Generator: Automated Invoicing Workflow

The Invoice Generator node simplifies the process of creating professional invoices. Let's build a workflow that automatically generates and sends invoices when new orders are created in Airtable.

Workflow Overview

  1. Airtable Trigger: Monitors for new orders with status "Ready to Invoice".
  2. Airtable Lookup: Fetches customer details and line items.
  3. Invoice Generator Node: Creates the invoice PDF.
  4. Email Node: Sends invoice to customer.
  5. Airtable Update: Marks order as "Invoiced".

Configuring the Invoice Generator

The Invoice Generator node requires structured data in specific fields. Here's how to configure each section:

Issuer Information

Company Name: Your Company Inc.
Address: 123 Business Street
City: San Francisco, CA 94105
Email: billing@yourcompany.com
Phone: (555) 123-4567

Recipient Information

Customer Name: {{ $json.customerName }}
Address: {{ $json.customerAddress }}
Email: {{ $json.customerEmail }}

Invoice Details

Invoice Number: INV-{{ $json.orderId }}
Invoice Date: {{ $now.format('YYYY-MM-DD') }}
Due Date: {{ $now.plus(30, 'days').format('YYYY-MM-DD') }}

Line Items

The Invoice Generator accepts line items in two modes: JSON or Individual Fields. For data from Airtable, JSON mode is typically easier:

// Items Input Mode: JSON
{{ $json.lineItems }}

// Expected format:
[
  {
    "description": "Web Development Services",
    "quantity": 40,
    "unitPrice": 150,
    "total": 6000
  },
  {
    "description": "Hosting (Annual)",
    "quantity": 1,
    "unitPrice": 500,
    "total": 500
  }
]

Payment Information

Payment Method: Bank Transfer
Bank Name: First National Bank
Account Number: 1234567890
Routing Number: 987654321
Notes: Payment due within 30 days

Advanced PDF Generation Techniques

Dynamic Data Injection

n8n's expression syntax allows you to inject data from previous nodes directly into your HTML templates. This makes it easy to create dynamic documents:

<h1>Welcome, {{ $json.firstName }}!</h1>
<p>Your order #{{ $json.orderId }} has been confirmed.</p>
<p>Total: ${{ $json.total.toFixed(2) }}</p>

Conditional Content

Use JavaScript in your Code node to include conditional content based on data:

const isPremium = $json.customerTier === 'Premium';

const html = `
  <div class="header">
    <h1>Invoice</h1>
    ${isPremium ? '<span class="badge">Premium Customer</span>' : ''}
  </div>
  
  ${isPremium ? `
    <div class="premium-benefits">
      <h3>Your Premium Benefits:</h3>
      <ul>
        <li>10% discount applied</li>
        <li>Priority support</li>
      </ul>
    </div>
  ` : ''}
`;

Multi-Page Documents

Create multi-page PDFs with headers and footers using CSS page rules:

<style>
  @page {
    margin: 2cm;
    @top-center {
      content: "Company Name - Confidential";
      font-size: 10px;
      color: #666;
    }
    @bottom-right {
      content: "Page " counter(page) " of " counter(pages);
      font-size: 10px;
    }
  }
  
  .page-break {
    page-break-after: always;
  }
</style>

<div class="section">
  <h2>Section 1</h2>
  <p>Content...</p>
</div>

<div class="page-break"></div>

<div class="section">
  <h2>Section 2</h2>
  <p>Content...</p>
</div>

Including Images and Logos

Embed images using base64 encoding or external URLs:

<!-- External URL -->
<img src="https://yourcompany.com/logo.png" alt="Company Logo" />

<!-- Base64 encoded -->
<img src="data:image/png;base64,{{ $json.logoBase64 }}" alt="Logo" />

Best Practices for PDF Generation in n8n

1. Optimize HTML for PDF Rendering

  • Use absolute units: Specify sizes in pixels or points rather than percentages for consistent rendering.
  • Inline CSS: While external stylesheets work, inline CSS ensures styles are always applied correctly.
  • Test fonts: Stick to web-safe fonts or embed custom fonts using @font-face with base64 encoding.
  • Avoid JavaScript: The PDF renderer executes HTML and CSS but doesn't run client-side JavaScript.

2. Handle Errors Gracefully

Add error handling to your workflows to manage failures:

  • Use n8n's error workflow feature to catch and log failures.
  • Add conditional logic to retry PDF generation if it fails.
  • Send notifications when critical invoice generation fails.
  • Store failed attempts in a database for manual review.

3. Manage File Storage

PDFs can be large files. Consider these storage strategies:

  • Cloud Storage: Upload PDFs to S3, Google Drive, or Dropbox for long-term storage.
  • Temporary URLs: CustomJS provides temporary download URLs that expire after 24 hours.
  • Database Storage: Store base64-encoded PDFs in databases for small files only.
  • Cleanup Workflows: Create scheduled workflows to delete old PDFs from storage.

4. Performance Optimization

  • Batch Processing: Generate multiple PDFs in parallel using n8n's Split In Batches node.
  • Minimize HTML Size: Remove unnecessary whitespace and comments from HTML templates.
  • Optimize Images: Compress images before embedding to reduce PDF file size.
  • Cache Templates: Store frequently used HTML templates in n8n variables or external storage.

5. Security Considerations

  • Sanitize Input: Always validate and sanitize data before injecting it into HTML to prevent XSS attacks.
  • Secure Webhooks: Use authentication headers or tokens to protect webhook endpoints.
  • Limit Access: Store sensitive PDFs in private storage with proper access controls.
  • Audit Trails: Log PDF generation events for compliance and debugging.

Common Use Cases for n8n PDF Generation

1. Automated Invoicing

Generate and send invoices automatically when orders are completed. Connect to your e-commerce platform, CRM, or database to pull order details, create professional invoices, and email them to customers—all without manual intervention.

2. Report Generation

Create scheduled reports from your data sources. Pull analytics from Google Analytics, sales data from your database, or metrics from monitoring tools, format them into readable reports, and distribute them to stakeholders via email or Slack.

3. Certificate Generation

Automatically generate certificates for course completions, event attendance, or achievements. When a user completes a course in your LMS, trigger a workflow that creates a personalized certificate with their name, course details, and completion date.

4. Contract Creation

Generate contracts from templates when deals are closed. Pull client information from your CRM, populate contract templates with specific terms and pricing, and create ready-to-sign PDF contracts.

5. Receipt Generation

Create receipts for payments or donations. When a payment is processed through Stripe or PayPal, automatically generate a receipt PDF and email it to the customer for their records.

6. Documentation Export

Convert documentation or wiki pages to PDF for offline access or archival. Fetch content from Notion, Confluence, or your CMS, format it properly, and generate PDF versions for distribution or backup.

Troubleshooting Common Issues

PDF Layout Issues

Problem: Content is cut off or doesn't fit on the page.

Solution: Adjust page margins and use CSS media queries for print. Set explicit page sizes:

@page {
  size: A4;
  margin: 2cm;
}

Images Not Displaying

Problem: Images appear as broken links in the PDF.

Solution: Use absolute URLs or base64-encoded images. Relative paths don't work in PDF generation:

// ❌ Won't work
<img src="/images/logo.png" />

// ✅ Will work
<img src="https://yoursite.com/images/logo.png" />

Font Rendering Issues

Problem: Custom fonts don't appear in the PDF.

Solution: Embed fonts using @font-face with base64 or use web-safe fonts like Arial, Times New Roman, or Courier.

Slow PDF Generation

Problem: PDFs take too long to generate.

Solution: Optimize your HTML by removing unnecessary elements, compressing images, and minimizing CSS. Consider using the Invoice Generator for simple invoices instead of custom HTML.

Data Not Appearing

Problem: Dynamic data doesn't show up in the PDF.

Solution: Check your n8n expressions. Use the expression editor to verify data paths. Common issues include:

  • Wrong node reference (use $json for current node data)
  • Incorrect property names (JavaScript is case-sensitive)
  • Missing data in previous nodes (check node outputs)

Cost Analysis: n8n PDF Generation vs Alternatives

Understanding the cost implications of different PDF generation approaches helps you make informed decisions for your business.

CustomJS with n8n Pricing

  • Free Tier: 600 PDFs per month at no cost
  • Paid Plans: Starting at $15/month for 5,000 PDFs
  • Cost per PDF: Approximately $0.003 per PDF at scale
  • No Hidden Fees: Flat pricing with no per-request charges

Alternative Services

  • DocRaptor: ~$15 per 1,000 PDFs (50x more expensive)
  • PDF.co: Starting at $9.99/month with usage limits
  • Api2Pdf: Pay-per-use with watermarks on free tier
  • ConvertAPI: Charges by megabyte, unpredictable costs

Cost Savings Example

For a business generating 10,000 invoices per month:

  • CustomJS: ~$30/month
  • DocRaptor: ~$150/month
  • Annual Savings: $1,440 by choosing CustomJS

These savings compound as your business scales, making CustomJS with n8n the most cost-effective solution for automated PDF generation.

Getting Started with n8n PDF Generation

Ready to automate your PDF generation? Here's your roadmap:

Step 1: Set Up n8n

If you don't have n8n yet, sign up for n8n.cloud to get started quickly. The hosted version includes community node support, which is required for CustomJS nodes.

Step 2: Install CustomJS Package

Navigate to Settings → Community Nodes and install @customjs/n8n-nodes. This adds the PDF generation nodes to your n8n instance.

Step 3: Import a Template

Start with one of the ready-made templates:

Step 4: Customize for Your Needs

Modify the template to connect to your data sources, adjust the PDF design, and configure email settings. Test with sample data before activating the workflow.

Step 5: Monitor and Optimize

Use n8n's execution history to monitor your workflows. Track success rates, identify errors, and optimize performance based on real usage patterns.

Conclusion

PDF generation in n8n transforms manual document creation into automated workflows that save time and reduce errors. Whether you're generating invoices, reports, certificates, or contracts, the combination of n8n's workflow automation and CustomJS's PDF generation capabilities provides a powerful, cost-effective solution.

The HTML to PDF node offers unlimited design flexibility for custom documents, while the Invoice Generator provides a ready-to-use solution for professional invoicing. Both approaches integrate seamlessly with your existing data sources and can be deployed in minutes using workflow templates.

With 600 free PDFs per month and predictable pricing beyond that, CustomJS makes automated PDF generation accessible to businesses of all sizes. The native n8n integration eliminates the complexity of external APIs, while the visual workflow interface makes automation maintainable by your entire team.

Start automating your PDF generation today by installing the CustomJS package in n8n and importing one of the workflow templates. Your first automated invoice, report, or certificate is just a few clicks away.

Frequently Asked Questions (FAQ)

How much does PDF generation in n8n cost?

CustomJS offers 600 free PDF generations per month. Paid plans start at $15/month for 5,000 PDFs, making it approximately $0.003 per PDF at scale. This is significantly cheaper than alternatives like DocRaptor ($15 per 1,000 PDFs) or PDF.co (starting at $9.99/month with strict limits).

Can I use CustomJS PDF nodes on self-hosted n8n?

No, CustomJS community nodes are only available on n8n.cloud (hosted version) due to security restrictions on self-hosted instances. However, you can use the CustomJS API directly via HTTP Request nodes in self-hosted n8n to achieve the same functionality.

What's the difference between HTML to PDF and Invoice Generator nodes?

The HTML to PDF node accepts custom HTML and CSS, giving you complete design control for any type of document. The Invoice Generator node provides a pre-built, professional invoice template where you only need to provide structured data (customer info, line items, etc.). Use HTML to PDF for custom designs and Invoice Generator for quick, standardized invoices.

Can I generate PDFs with dynamic data from Airtable or databases?

Yes! n8n connects to hundreds of data sources including Airtable, PostgreSQL, MySQL, Google Sheets, and REST APIs. You can fetch data from any source, transform it as needed, and inject it into your PDF templates using n8n's expression syntax. The workflow templates provided show exactly how to do this with Airtable.

How long does it take to generate a PDF in n8n?

PDF generation typically takes 2-5 seconds depending on document complexity and size. CustomJS is 2-3x faster than alternatives like PDF.co. For bulk generation, you can process multiple PDFs in parallel using n8n's Split In Batches node to improve throughput.

Can I include images and logos in my PDFs?

Yes, you can include images using either external URLs (https://yoursite.com/logo.png) or base64-encoded images. For best results, use absolute URLs or embed images as base64 strings. Relative paths won't work in PDF generation.

What happens to generated PDFs? Are they stored permanently?

CustomJS provides temporary download URLs that expire after 24 hours. For permanent storage, you should upload PDFs to your own cloud storage (S3, Google Drive, Dropbox) using n8n's storage nodes. The PDF is also available as binary data within your workflow for immediate use (email attachments, etc.).

Can I automate invoice sending with payment links?

Absolutely! You can generate invoices with embedded payment links (Stripe, PayPal, etc.) and automatically email them to customers. The workflow can also update your database or Airtable when invoices are sent, creating a complete automated billing system.

Is there a limit on PDF file size or page count?

There's no strict page limit, but very large PDFs (100+ pages) may take longer to generate. For optimal performance, keep PDFs under 50 pages and 10MB. If you need to generate large documents, consider splitting them into multiple PDFs or optimizing images and content.

Can I use custom fonts in my PDFs?

Yes, you can use custom fonts by embedding them with @font-face in your CSS using base64-encoded font files or external URLs. Alternatively, stick to web-safe fonts (Arial, Times New Roman, Courier, Georgia) for guaranteed compatibility without additional setup.