UNPKG

n8n-nodes-json-html-to-pdf

Version:

Professional n8n node to convert JSON data or HTML content to PDF documents with Handlebars template support

392 lines (309 loc) 10.7 kB
# n8n-nodes-json-html-to-pdf [![NPM Version](https://img.shields.io/npm/v/n8n-nodes-json-html-to-pdf.svg)](https://www.npmjs.com/package/n8n-nodes-json-html-to-pdf) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![n8n](https://img.shields.io/badge/n8n-node-FF6D5A)](https://n8n.io) [![Made with Love](https://img.shields.io/badge/Made%20with-❤️-red.svg)](https://rhod.expert) Professional n8n community node that converts JSON data or HTML content to PDF documents. Built with over 30 years of development experience, this node provides enterprise-grade PDF generation with Handlebars template support, perfect for invoices, reports, certificates, and any document automation needs. **Created by [Rodrigo Vieira da Costa](https://rhod.expert) - Senior Full Stack Developer | Automation Specialist** ## Features - **Dual Input Support**: Accept either JSON data with Handlebars templates or raw HTML - **Flexible Output**: Generate PDFs as binary data or base64 strings - **Customizable Formatting**: Control page size, margins, orientation, and more - **Advanced Options**: Add headers/footers, custom CSS, and wait for specific elements - **Template Engine**: Use Handlebars for dynamic content generation - **Production Ready**: Built with Puppeteer for reliable PDF generation ## Installation ### Community Node (Recommended) 1. Go to **Settings** > **Community Nodes** 2. Search for `n8n-nodes-json-html-to-pdf` 3. Click **Install** ### Manual Installation ```bash npm install n8n-nodes-json-html-to-pdf ``` Then restart your n8n instance. ### Docker Installation If you're using n8n with Docker, you'll need to install Puppeteer dependencies: ```dockerfile FROM n8nio/n8n:latest USER root RUN apk add --no-cache \ chromium \ nss \ freetype \ freetype-dev \ harfbuzz \ ca-certificates \ ttf-freefont ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true \ PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser USER node RUN npm install n8n-nodes-json-html-to-pdf ``` ## Node Reference ### Input Types #### JSON with Template Use JSON data with a Handlebars template to generate dynamic PDFs. **Example JSON:** ```json { "title": "Invoice #2025-001", "customer": { "name": "Rhod Expert", "address": "123 Main St, City, Country" }, "items": [ { "description": "Product A", "quantity": 2, "price": 50.00 }, { "description": "Product B", "quantity": 1, "price": 75.00 } ], "total": 175.00 } ``` **Example Template:** ```html <!DOCTYPE html> <html> <head> <style> body { font-family: Arial, sans-serif; padding: 40px; } .header { border-bottom: 2px solid #333; margin-bottom: 20px; } table { width: 100%; border-collapse: collapse; } th, td { padding: 10px; text-align: left; } th { background-color: #f0f0f0; } .total { font-weight: bold; font-size: 1.2em; } </style> </head> <body> <div class="header"> <h1>{{title}}</h1> <p>{{customer.name}}<br>{{customer.address}}</p> </div> <table> <thead> <tr> <th>Description</th> <th>Quantity</th> <th>Price</th> <th>Subtotal</th> </tr> </thead> <tbody> {{#each items}} <tr> <td>{{description}}</td> <td>{{quantity}}</td> <td>${{price}}</td> <td>${{multiply quantity price}}</td> </tr> {{/each}} </tbody> </table> <p class="total">Total: ${{total}}</p> </body> </html> ``` #### Raw HTML Directly convert HTML content to PDF without templating. ### Output Formats - **Binary**: Returns the PDF as a binary file attachment (recommended for file operations) - **Base64**: Returns the PDF as a base64 encoded string in the JSON output ### Options | Option | Description | Default | |--------|-------------|---------| | **Page Format** | Paper size (A3, A4, A5, Letter, Legal, Tabloid) | A4 | | **Landscape** | Use landscape orientation | false | | **Scale** | Scale of webpage rendering (0.1 - 2.0) | 1.0 | | **Margins** | Top, bottom, left, right margins | 20px | | **Print Background** | Include background graphics | true | | **Custom CSS** | Additional CSS to inject | - | | **Wait Until** | When to consider page loaded | networkidle0 | | **Wait For Selector** | CSS selector to wait for | - | | **Header/Footer** | Custom header and footer templates | - | ## Usage Examples ### Example 1: Generate Invoice PDF ```json // Input Node Configuration { "inputType": "jsonTemplate", "jsonData": { "invoiceNumber": "INV-2024-001", "date": "2024-01-15", "items": [ {"name": "Service A", "amount": 500}, {"name": "Service B", "amount": 300} ], "total": 800 }, "outputFormat": "binary", "fileName": "invoice-2024-001.pdf", "options": { "format": "A4", "marginTop": "40px", "marginBottom": "40px" } } ``` ### Example 2: Convert HTML Report to PDF ```json // Input Node Configuration { "inputType": "html", "htmlContent": "<html><body><h1>Monthly Report</h1><p>Report content...</p></body></html>", "outputFormat": "binary", "fileName": "monthly-report.pdf", "options": { "format": "Letter", "landscape": true, "displayHeaderFooter": true, "headerTemplate": "<div style='font-size: 10px;'>Monthly Report - Page <span class='pageNumber'></span></div>" } } ``` ### Example 3: Generate Certificate with Custom Styling ```json // Input Node Configuration { "inputType": "jsonTemplate", "jsonData": { "recipientName": "Jane Smith", "courseName": "Advanced n8n Workflows", "completionDate": "2024-01-20" }, "htmlTemplate": "<!-- Certificate template HTML -->", "outputFormat": "binary", "fileName": "certificate.pdf", "options": { "format": "A4", "landscape": true, "customCss": ".certificate { border: 5px solid gold; padding: 50px; }", "printBackground": true } } ``` ## Workflow Integration ### Basic Workflow Structure 1. **Trigger Node** → 2. **Data Source** → 3. **JSON/HTML to PDF** → 4. **Output/Storage** ### Integration with Other Nodes #### Email Attachment ``` Webhook → JSON/HTML to PDF → Send Email (with PDF attachment) ``` #### Save to Storage ``` Database Query → JSON/HTML to PDF → AWS S3 / Google Drive ``` #### Batch Processing ``` Spreadsheet → Split in Batches → JSON/HTML to PDF → Merge ``` ## Handlebars Helpers The node includes standard Handlebars helpers. You can use: - `{{#if}}` / `{{#unless}}` - Conditional rendering - `{{#each}}` - Iterate over arrays - `{{#with}}` - Change context - `{{> partialName}}` - Include partials ### Custom Helpers Example For advanced templating, you can register custom helpers in your template: ```html <script> Handlebars.registerHelper('formatCurrency', function(amount) { return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(amount); }); </script> ``` ## Troubleshooting ### Common Issues #### 1. PDF Generation Timeout **Problem**: Large or complex HTML takes too long to render **Solution**: - Increase the timeout in node settings - Simplify HTML/CSS - Use `waitUntil: 'domcontentloaded'` instead of `'networkidle0'` #### 2. Missing Fonts or Characters **Problem**: Special characters or fonts not rendering **Solution**: - Embed fonts using base64 in CSS - Use web-safe fonts - Install required fonts in Docker container #### 3. Memory Issues **Problem**: Out of memory errors with large PDFs **Solution**: - Process items in smaller batches - Reduce image sizes in HTML - Increase Node.js memory limit #### 4. Docker Permissions **Problem**: Puppeteer fails to launch in Docker **Solution**: ```dockerfile RUN chmod -R 777 /tmp ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true ENV PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser ``` ### Debug Mode Enable debug output by setting environment variable: ```bash DEBUG=puppeteer:* n8n start ``` ## Performance Tips 1. **Reuse Templates**: Store templates in a separate node or file 2. **Optimize Images**: Use base64 for small images, URLs for large ones 3. **Batch Processing**: Process multiple items in parallel when possible 4. **Cache Static Content**: Store frequently used CSS/JS separately ## Security Considerations - **Sanitize Input**: Always validate and sanitize user-provided HTML - **Limit Resources**: Set appropriate timeouts and memory limits - **Sandbox Environment**: Puppeteer runs in a sandboxed environment by default - **Access Control**: Restrict file system access in production ## Contributing Contributions are welcome! Please feel free to submit a Pull Request. 1. Fork the repository 2. Create your feature branch (`git checkout -b feature/AmazingFeature`) 3. Commit your changes (`git commit -m 'Add some AmazingFeature'`) 4. Push to the branch (`git push origin feature/AmazingFeature`) 5. Open a Pull Request ## Support For issues and feature requests, please use the [GitHub issues page](https://github.com/rhodexpert/n8n-nodes-json-html-to-pdf/issues). ## License This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. ## Acknowledgments - Built for the [n8n](https://n8n.io) workflow automation platform - Uses [Puppeteer](https://pptr.dev/) for PDF generation - Templating powered by [Handlebars](https://handlebarsjs.com/) ## 👨‍💻 Author **Rodrigo Vieira da Costa** - 🌐 Website: [rhod.expert](https://rhod.expert) - 📧 Email: rhod@rhod.expert - 💼 GitHub: [@rhod-expert](https://github.com/rhod-expert) - 🏢 Company: RHOD EXPERT SOLUCOES EM TECNOLOGIA - 📍 Location: Iguassu Falls, Paraná, Brazil Senior Full Stack Developer with 30+ years of experience, specializing in automation, system integration, and creating tools that boost productivity. ## ⭐ Show your support Give a ⭐️ if this project helped you! Your support motivates me to keep improving this node. ## Changelog ### v0.1.0 (2025-01) - Initial release - JSON to PDF conversion with Handlebars templates - Raw HTML to PDF conversion - Customizable page formatting - Binary and base64 output formats - Header/footer support - Custom CSS injection - Professional invoice and report templates included - Comprehensive test suite --- <p align="center"> Made with ❤️ by <a href="https://rhod.expert">Rodrigo Vieira da Costa</a><br> <em>"Automatizando o presente, construindo o futuro"</em><br> <em>(Automating the present, building the future)</em> </p>