Skip to content

A high-performance Node.js PDF generation service using Puppeteer with dynamic sizing capabilities and REST API

Notifications You must be signed in to change notification settings

LayishSieger/pdf-service-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

RenderPDF Service

A high-performance Node.js PDF generation service using Puppeteer with dynamic sizing capabilities, designed for deployment on Render.com.

Features

  • Dynamic Height Calculation: Automatically adjusts PDF height based on content length
  • Multiple Page Formats: Support for A4, Letter, Legal, A3, A5, Tabloid, and custom dimensions
  • CORS Support: Configurable cross-origin request handling
  • Production Ready: Optimized for Render.com deployment with proper error handling
  • Health Monitoring: Built-in health check endpoints for monitoring
  • Rate Limiting: Configurable request rate limiting
  • Security: Helmet.js security headers and input validation

Quick Start

Prerequisites

  • Node.js 18.0.0 or higher
  • npm or yarn package manager

Installation

  1. Clone the repository:
git clone <repository-url>
cd renderPDF
  1. Install dependencies:
npm install
  1. Copy environment configuration:
cp env.example .env
  1. Start the service:
# Development mode
npm run dev

# Production mode
npm start

The service will be available at http://localhost:3000

API Endpoints

Health Check

GET /health

Returns service health status and uptime information.

Generate PDF

POST /api/pdf/generate

Converts HTML content to PDF with configurable options.

Request Body:

{
  "html": "<html><body><h1>Hello World</h1></body></html>",
  "format": "A4",
  "orientation": "portrait",
  "margins": {
    "top": 0.5,
    "right": 0.5,
    "bottom": 0.5,
    "left": 0.5
  },
  "filename": "document.pdf"
}

Response: PDF file download

Get Supported Formats

GET /api/pdf/formats

Returns list of supported page formats.

Custom PDF Generation

POST /api/pdf/custom

Generate PDF with custom dimensions.

Request Body:

{
  "html": "<html><body><h1>Custom Size</h1></body></html>",
  "width": 8.5,
  "height": 11,
  "orientation": "portrait",
  "margins": {
    "top": 0.25,
    "right": 0.25,
    "bottom": 0.25,
    "left": 0.25
  }
}

PDF Service Health

GET /api/pdf/health

Returns PDF generation service health status.

Supported Page Formats

Format Width (inches) Height (inches) Description
A4 8.27 11.69 International standard
Letter 8.5 11 US standard
Legal 8.5 14 US legal
A3 11.69 16.54 Large format
A5 5.83 8.27 Small format
Tabloid 11 17 Large US format

Configuration

Environment Variables

Copy env.example to .env and configure:

  • PORT: Server port (default: 3000)
  • NODE_ENV: Environment (development/production)
  • ALLOWED_ORIGINS: CORS allowed origins (comma-separated)
  • RATE_LIMIT_MAX: Maximum requests per 15 minutes
  • MAX_REQUEST_SIZE: Maximum request size
  • PUPPETEER_ARGS: Additional Puppeteer browser arguments

Puppeteer Configuration

The service is pre-configured for Render.com deployment with optimized browser arguments:

--no-sandbox --disable-setuid-sandbox --disable-dev-shm-usage --disable-accelerated-2d-canvas --no-first-run --no-zygote --disable-gpu --single-process

Dynamic Sizing

The service automatically calculates the optimal PDF height based on content:

  1. Content Rendering: HTML content is rendered in a browser instance
  2. Height Measurement: Actual content height is measured after rendering
  3. PDF Generation: PDF is generated with calculated dimensions
  4. Optimization: Ensures content fits without unnecessary page breaks

Deployment on Render.com

1. Create New Web Service

  1. Connect your GitHub repository
  2. Select "Web Service" as the service type
  3. Choose the repository branch

2. Build Configuration

  • Build Command: npm install
  • Start Command: npm start
  • Environment: Node

3. Environment Variables

Set these in Render.com dashboard:

NODE_ENV=production
PORT=10000
PUPPETEER_ARGS=--no-sandbox --disable-setuid-sandbox --disable-dev-shm-usage

4. Health Check

Configure health check endpoint:

  • Path: /health
  • Interval: 30 seconds

Development

Scripts

npm run dev      # Start development server with nodemon
npm start        # Start production server
npm test         # Run tests
npm run lint     # Run ESLint
npm run format   # Format code with Prettier

Project Structure

renderPDF/
├── server.js              # Main Express server
├── routes/
│   └── pdf.js            # PDF generation routes
├── services/
│   └── pdfGenerator.js   # Puppeteer PDF service
├── middleware/
│   ├── validation.js     # Request validation
│   └── errorHandler.js   # Error handling
├── utils/
│   └── pageFormats.js    # Page format utilities
├── package.json
├── env.example
├── render.yaml
└── README.md

Error Handling

The service includes comprehensive error handling:

  • Validation Errors: 400 Bad Request for invalid input
  • PDF Generation Errors: 500 Internal Server Error
  • Service Unavailable: 503 Service Unavailable
  • Rate Limiting: 429 Too Many Requests
  • Content Too Large: 413 Payload Too Large

Performance Optimization

  • Browser Instance Reuse: Single browser instance for multiple requests
  • Memory Management: Automatic cleanup of page instances
  • Compression: Response compression for large PDFs
  • Rate Limiting: Prevents abuse and ensures stability

Security Features

  • Input Validation: Comprehensive request validation
  • CORS Configuration: Configurable cross-origin access
  • Rate Limiting: Request throttling
  • Security Headers: Helmet.js security middleware
  • Content Sanitization: Input sanitization and validation

Monitoring and Health Checks

Health Endpoints

  • /health: Overall service health
  • /api/pdf/health: PDF generation service health

Health Check Response

{
  "success": true,
  "service": "RenderPDF Service",
  "status": "running",
  "timestamp": "2024-01-01T00:00:00.000Z",
  "uptime": 3600,
  "environment": "production",
  "version": "1.0.0"
}

Troubleshooting

Common Issues

  1. Browser Launch Failures: Check Puppeteer arguments and system dependencies
  2. Memory Issues: Reduce concurrent requests or increase system memory
  3. Timeout Errors: Check content complexity and browser timeout settings
  4. CORS Errors: Verify ALLOWED_ORIGINS configuration

Logs

Enable verbose logging by setting:

DEBUG=true
VERBOSE_LOGGING=true

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

License

MIT License - see LICENSE file for details.

Support

For issues and questions:

  • Create an issue in the GitHub repository
  • Check the troubleshooting section
  • Review the API documentation

Note: This service is optimized for Render.com deployment. For other platforms, you may need to adjust Puppeteer arguments and configuration settings.

About

A high-performance Node.js PDF generation service using Puppeteer with dynamic sizing capabilities and REST API

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published