Sign inSign up

bagose/html-to-pdf-api

By bagose

โ€ขUpdated 7 months ago

API to convert HTML receipts to PDF using Puppeteer

Image
Integration & delivery
Developer tools
0

1.8K

bagose/html-to-pdf-api repository overview

HTML to PDF API Banner

โ ๐Ÿ“„ HTML to PDF API

v7.2.2 โ€” Unified Gateway & Logo Injection

Enterprise-grade document generation & processing API. Convert HTML, URLs, and templates into professional PDFs and images with a single endpoint.

Node.js Puppeteer Docker Docker Pulls Docker Stars License: MIT


โ โšก Architecture Overview

Version 7.2.2 consolidates 20+ legacy endpoints into two core gateways:

EndpointPurposeMethod
/renderGenerate PDFs or Images from any sourcePOST
/pdf-actionPost-process existing PDF filesPOST

Plus background job processing via /queue, /jobs/:id, and /queue/stats.


โ ๐Ÿš€ Quick Start

Pull from Docker Hub:

docker pull bagose/html-to-pdf-api:latest

Running with Docker Compose:

docker-compose up -d

The API will be available at http://localhost:3000. Official Image: bagose/html-to-pdf-apiโ 

โ Local Development
# Install dependencies
npm install

# Start development server with hot-reload
npm run dev

# Or start production
npm start
โ Environment Variables

Create a .env file (all optional with sensible defaults):

# Server
PORT=3000
MAX_BODY_SIZE=10mb
AUTO_CLEANUP_HOURS=24

# Security (โš ๏ธ Change in production!)
ADMIN_USERNAME=admin
ADMIN_PASSWORD=admin123
JWT_SECRET=html-to-pdf-secret-key-change-in-production
SIGNED_URL_SECRET=signed-url-secret-change-me
SIGNED_URL_EXPIRY_MINUTES=60
CORS_ORIGINS=*

# Browser
PUPPETEER_EXECUTABLE_PATH=    # Auto-detected
BROWSER_POOL_SIZE=1

# Queue
QUEUE_CONCURRENCY=3

# Email (optional)
SMTP_HOST=
SMTP_PORT=587
SMTP_USER=
SMTP_PASS=
SMTP_FROM=

# Cloud Storage โ€” S3-compatible (optional)
STORAGE_PROVIDER=local
STORAGE_ENDPOINT=
STORAGE_BUCKET=
STORAGE_REGION=us-east-1
STORAGE_ACCESS_KEY=
STORAGE_SECRET_KEY=
STORAGE_PATH_PREFIX=
STORAGE_KEEP_LOCAL=true

โ ๐Ÿ“– API Reference

โ 1. POST /render โ€” Universal Renderer

Generate PDFs or images from HTML, URLs, or Templates. Supports inline Charts, Tables, QR Codes, Barcodes, and Watermarks.

โ Request Body
FieldTypeRequiredDescription
source_typestringโœ…html, url, or template
sourcestringโœ…HTML content, URL, or template name
outputstringpdf (default) or image
dataobjectTemplate variables
filenamestringCustom output filename
asyncbooleanIf true, processes in background & returns job_id
signed_urlobject{ expiry_minutes: 60 } for time-limited access
cloud_uploadbooleanUpload to configured S3-compatible storage
optionsobjectRendering options (see below)
โ Render Options
OptionTypeDescription
pageSizestringa4, a5, letter, legal, label, sertifikat, thermal_58mm, thermal_80mm, thermal_default
landscapebooleanLandscape orientation
marginobject{ top, bottom, left, right }
inject_cssstringCustom CSS to inject into the page
watermarkobject{ text, opacity, color, fontSize, rotate, repeat } โ€” Overlay watermark. Set repeat: true to tile text across entire page
chartobjectChart.js configuration: { data: { type, data, options }, width, height }
tableobject{ data: [...], options: { columns, headers, zebra } }
qr_codeobject{ text, position, width, label, color, background }
barcodeobject{ text, type, position, label, scale, height }
logoobject{ src, width, height, position, grayscale, opacity, margin } โ€” Universal image injection (URL or Base64)
displayHeaderFooterbooleanEnable header/footer templates
headerTemplatestringHTML template for page header
footerTemplatestringHTML template for page footer
return_base64booleanInclude base64 data in response
formatstringImage format: png, jpeg, webp
qualityintegerImage quality (0-100)
fullPagebooleanFull page screenshot (default: true)
โ Examples

HTML โ†’ PDF

{
  "source_type": "html",
  "source": "<h1>Monthly Report</h1><p>Generated on 2026-02-13</p>",
  "options": {
    "pageSize": "a4",
    "margin": { "top": "20mm", "bottom": "20mm", "left": "15mm", "right": "15mm" }
  }
}

URL โ†’ Screenshot

{
  "source_type": "url",
  "source": "https://github.com",
  "output": "image",
  "options": { "format": "png", "fullPage": true }
}

Template โ†’ Receipt PDF

{
  "source_type": "template",
  "source": "indomaret",
  "data": {
    "store_name": "My Store",
    "cashier": "John",
    "items": [
      { "name": "Coffee", "qty": 2, "price": 15000 },
      { "name": "Bread", "qty": 1, "price": 12000 }
    ],
    "payment": 50000
  }
}

HTML + Embedded Chart

{
  "source_type": "html",
  "source": "<h1>Sales Dashboard</h1>",
  "options": {
    "pageSize": "a4",
    "chart": {
      "data": {
        "type": "bar",
        "data": {
          "labels": ["Q1", "Q2", "Q3", "Q4"],
          "datasets": [{
            "label": "Revenue ($K)",
            "data": [120, 190, 150, 210],
            "backgroundColor": ["#6366f1", "#8b5cf6", "#a78bfa", "#c4b5fd"]
          }]
        }
      },
      "width": 700,
      "height": 350
    }
  }
}

PDF with QR Code & Watermark

{
  "source_type": "html",
  "source": "<h1>Official Document</h1><p>Content here...</p>",
  "options": {
    "pageSize": "a4",
    "qr_code": {
      "text": "https://verify.example.com/doc/12345",
      "position": "bottom-right",
      "label": "Scan to verify"
    },
    "watermark": { "text": "CONFIDENTIAL", "opacity": 0.08 }
  }
}

PDF with Barcode

{
  "source_type": "html",
  "source": "<h1>Product Label</h1>",
  "options": {
    "pageSize": "label",
    "barcode": {
      "text": "SKU-999-XYZ",
      "type": "code39",
      "position": "bottom-center",
      "width": 2,
      "height": 40,
      "displayValue": true
    }
  }
}

Receipt with Repeating Watermark (Thermal Paper)

{
  "source_type": "template",
  "source": "indomaret",
  "data": {
    "store_name": "My Coffee Shop",
    "items": [{ "name": "Espresso", "qty": 2, "price": 35000 }],
    "payment": 100000
  },
  "options": {
    "pageSize": "thermal_80mm",
    "qr_code": { "text": "ORDER-12345", "position": "bottom-center" },
    "watermark": {
      "text": "My Coffee Shop",
      "repeat": true,
      "opacity": 0.08
    }
  }
}

The repeat: true option tiles the watermark text diagonally across the entire receipt, perfect for store branding.


โ 2. POST /pdf-action โ€” Universal Processor

Post-process existing PDF files with 9 available actions.

โ Actions
ActionDescriptionRequired Options
compressReduce file sizequality: screen, ebook, printer, default
encryptAdd password protectionpassword
signEmbed signature stamp imagesignature_name or signature_base64, position
mergeCombine multiple PDFsUse files array instead of filename
splitSplit into individual pagesโ€”
extractExtract specific pagespages: [0, 2, "4-6"]
metadataRead/write PDF metadatatitle, author, subject, keywords, creator
thumbnailGenerate page previewwidth, height, page, format, return_base64
emailSend PDF via SMTPto, subject, message, cc, bcc
โ Examples

Compress

{ "action": "compress", "filename": "report.pdf", "options": { "quality": "ebook" } }

Merge

{ "action": "merge", "files": ["cover.pdf", "chapter1.pdf", "chapter2.pdf"] }

Password Protect

{ "action": "encrypt", "filename": "contract.pdf", "options": { "password": "s3cur3!" } }

Sign with Stamp

{
  "action": "sign",
  "filename": "contract.pdf",
  "options": {
    "signature_name": "ceo",
    "position": "bottom-right",
    "width": 150,
    "height": 75,
    "page": 0
  }
}

Extract Pages

{ "action": "extract", "filename": "book.pdf", "options": { "pages": [0, 1, "5-10"] } }

Read Metadata

{ "action": "metadata", "filename": "document.pdf" }

Set Metadata

{
  "action": "metadata",
  "filename": "report.pdf",
  "options": { "title": "Annual Report 2025", "author": "Finance Team" }
}

Email PDF

{
  "action": "email",
  "filename": "invoice.pdf",
  "options": {
    "to": "[email protected]",
    "subject": "Your Invoice",
    "message": "Please find your invoice attached."
  }
}

Thumbnail

{
  "action": "thumbnail",
  "filename": "presentation.pdf",
  "options": { "width": 300, "page": 1, "format": "png" }
}

โ 3. Background Queue

For heavy operations, submit jobs to the async queue:

Submit Job

POST /queue
{ "type": "render", "data": { "html_content": "<h1>Heavy Report</h1>", "options": { "pageSize": "a4" } }, "priority": 5 }

Check Status

GET /jobs/{job_id}

Queue Stats

GET /queue/stats

โ 4. Legacy Endpoint

POST /cetak_struk_pdf โ€” Backward-compatible receipt generator.

Supports: html_content, template, qr_code, barcode, logo, and watermark (including repeat).

{
  "html_content": "<div>My receipt HTML</div>",
  "page_size": "thermal_80mm",
  "qr_code": { "text": "INV-001", "position": "bottom-center" }
}

Or use a built-in template:

{
  "template": "indomaret",
  "data": {
    "store_name": "Toko Jaya",
    "items": [{ "name": "Mie Instan", "qty": 3, "price": 3500 }],
    "payment": 15000
  }
}

โ ๐ŸŽจ Built-in Templates

TemplateDescriptionDefault Size
indomaretRetail receipt (Indonesian style)thermal_default
invoiceProfessional invoicea4
modernModern document layouta4
suratIndonesian formal lettera4
labelShipping labellabel
sertifikatCertificate (landscape)sertifikat

Create custom templates via the Admin Panel at /admin-panel โ†’ Templates.


โ ๐Ÿ”’ Security

FeatureDescription
API Key AuthOptional key-based access control with quotas and rate limits
Password ProtectionEncrypt PDFs with AES-256 via qpdf
Digital SignaturesEmbed stamp images with configurable position and opacity
Signed URLsTime-limited, tamper-proof file access URLs
CORSConfigurable origin whitelist
Helmet.jsSecurity headers (CSP, HSTS, etc.)
Rate LimitingPer-endpoint request throttling
Input SanitizationHTML sanitization to prevent XSS

โ ๐Ÿ“Š Admin Dashboard

Access at /admin-panel with your admin credentials.

Features:

  • ๐Ÿ“ˆ Real-time request statistics and endpoint usage charts
  • ๐Ÿ”‘ API key management (create, edit, delete, quotas)
  • ๐Ÿ“ Request logs with filtering
  • ๐Ÿ“‚ File manager (view, download, delete generated files)
  • ๐ŸŽจ Custom template editor with live preview
  • โš™๏ธ Global settings (guest access, maintenance mode, cleanup schedule)
  • ๐Ÿ”ง System info and capabilities overview

โ ๐Ÿณ Docker Deployment

โ docker-compose.yml
version: "3.8"
services:
  html-to-pdf-api:
    build: .
    image: bagose/html-to-pdf-api:7.2.1
    ports:
      - "3000:3000"
    environment:
      - ADMIN_PASSWORD=your_secure_password
      - JWT_SECRET=your_jwt_secret
      - SIGNED_URL_SECRET=your_signed_url_secret
    volumes:
      - pdf_output:/app/output
      - pdf_data:/app/data
    deploy:
      resources:
        limits:
          memory: 1G

volumes:
  pdf_output:
  pdf_data:
โ Resource Requirements
ResourceMinimumRecommended
RAM256 MB512 MB โ€“ 1 GB
CPU0.5 cores1+ cores
Storage100 MB1 GB+ (depends on output volume)

โ ๐Ÿ—๏ธ Project Structure

โ”œโ”€โ”€ server.js              # Entry point & graceful shutdown
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ app.js             # Express setup, middleware, security
โ”‚   โ”œโ”€โ”€ config.js          # Environment configuration & constants
โ”‚   โ”œโ”€โ”€ swagger.js         # OpenAPI 3.0 documentation
โ”‚   โ”œโ”€โ”€ admin/
โ”‚   โ”‚   โ””โ”€โ”€ index.html     # Admin dashboard SPA
โ”‚   โ”œโ”€โ”€ routes/
โ”‚   โ”‚   โ”œโ”€โ”€ index.js       # Route aggregator
โ”‚   โ”‚   โ”œโ”€โ”€ universal.js   # Core: /render, /pdf-action, /queue
โ”‚   โ”‚   โ”œโ”€โ”€ files.js       # File management
โ”‚   โ”‚   โ”œโ”€โ”€ admin.js       # Admin endpoints
โ”‚   โ”‚   โ””โ”€โ”€ health.js      # Health check
โ”‚   โ”œโ”€โ”€ services/
โ”‚   โ”‚   โ”œโ”€โ”€ renderer.js    # Puppeteer rendering engine
โ”‚   โ”‚   โ”œโ”€โ”€ browser.js     # Browser pool management
โ”‚   โ”‚   โ”œโ”€โ”€ pdfUtils.js    # Merge, protect, compress
โ”‚   โ”‚   โ”œโ”€โ”€ pdfAdvanced.js # Split, extract pages
โ”‚   โ”‚   โ”œโ”€โ”€ pdfMetadata.js # Read/write PDF metadata
โ”‚   โ”‚   โ”œโ”€โ”€ signature.js   # Digital signature stamps
โ”‚   โ”‚   โ”œโ”€โ”€ chart.js       # Chart.js rendering
โ”‚   โ”‚   โ”œโ”€โ”€ table.js       # Auto-paginated tables
โ”‚   โ”‚   โ”œโ”€โ”€ qrBarcode.js   # QR code & barcode generation
โ”‚   โ”‚   โ”œโ”€โ”€ thumbnail.js   # PDF thumbnail generation
โ”‚   โ”‚   โ”œโ”€โ”€ email.js       # SMTP email service
โ”‚   โ”‚   โ”œโ”€โ”€ queue.js       # In-memory job queue
โ”‚   โ”‚   โ”œโ”€โ”€ cloudStorage.js# S3-compatible cloud upload
โ”‚   โ”‚   โ”œโ”€โ”€ signedUrl.js   # Signed URL generation
โ”‚   โ”‚   โ”œโ”€โ”€ fileManager.js # File operations & cleanup
โ”‚   โ”‚   โ”œโ”€โ”€ stats.js       # Request statistics
โ”‚   โ”‚   โ”œโ”€โ”€ apiKey.js      # API key management
โ”‚   โ”‚   โ”œโ”€โ”€ settings.js    # Runtime settings
โ”‚   โ”‚   โ””โ”€โ”€ customTemplate.js # Custom template CRUD
โ”‚   โ”œโ”€โ”€ templates/         # Built-in receipt & document templates
โ”‚   โ”œโ”€โ”€ middleware/         # Auth, rate limiting, sanitization
โ”‚   โ””โ”€โ”€ utils/             # Response helpers, formatters
โ”œโ”€โ”€ docker-compose.yml
โ”œโ”€โ”€ Dockerfile
โ””โ”€โ”€ package.json

โ ๐Ÿ“ก System Endpoints

EndpointDescription
GET /API info & endpoint directory
GET /healthSystem health, memory, browser status
GET /docsInteractive Swagger UI
GET /templatesAvailable templates & capabilities
GET /filesList generated files
POST /cleanupRemove old files
GET /admin-panelAdmin dashboard

โ ๐Ÿงช Testing

# Basic render test
curl -X POST http://localhost:3000/render \
  -H "Content-Type: application/json" \
  -d '{"source_type":"html","source":"<h1>Test</h1>","options":{"pageSize":"a4"}}'

# Health check
curl http://localhost:3000/health

# List templates
curl http://localhost:3000/templates

โ ๐Ÿ“‹ Changelog

โ v7.2.2 โ€” Logo, Watermark & Receipt Perfection
  • ๐Ÿ–ผ๏ธ Universal Logo Injection: Add logos to any PDF/Image via URL/Base64 on ALL endpoints (including legacy)
  • ๐Ÿ“œ Dynamic Long Receipt: Auto-expanding height for thermal receipts (no more clipping on long lists!)
  • ๐ŸŒŠ Repeating Watermarks: Added repeat: true for diagonal tiling (supported in /render & /cetak_struk_pdf)
  • ๐Ÿ”„ Legacy Upgrade: POST /cetak_struk_pdf now supports logo parameter
  • ๐Ÿ› ๏ธ Bug Fixes: Resolved CSS overflow issues and improved image loading reliability
  • ๐Ÿ“ Updated all metadata to version 7.2.2
โ v7.2.0 โ€” Unified Gateway Architecture
  • ๐Ÿ—๏ธ Consolidated 20+ endpoints into /render and /pdf-action
  • ๐Ÿ“Š Added Chart.js integration for automated chart generation
  • ๐Ÿ“‹ Added auto-paginated table generation
  • ๐Ÿ” Added extract pages and digital signature stamp actions
  • โ˜๏ธ Added optional S3-compatible cloud storage upload
  • ๐Ÿ”— Added signed URL generation for secure file access
  • ๐Ÿ“ง Integrated email delivery as a PDF action
  • ๐Ÿ–ผ๏ธ Added PDF thumbnail preview generation
  • ๐Ÿ“ Added PDF metadata read/write
  • โšก Background job queue with priority support
  • ๐Ÿš€ New: Automatic Queueing via async: true in /render
  • ๐Ÿ› ๏ธ Optimization: Added Chromium "Lite Mode" flags for 30% less RAM usage
  • ๐ŸŽจ Admin dashboard with template editor
  • ๐Ÿงน Removed 8 legacy route files for cleaner codebase

โ ๐ŸŽ๏ธ Resource Optimization (Lite Mode)

Version 7.2.2 is optimized for low-resource environments (VPS/Container):

  • Chromium Lite Mode: We use specialized flags (--disable-extensions, --no-first-run, etc.) to minimize memory footprint.
  • Concurrency Control: Use QUEUE_CONCURRENCY and BROWSER_POOL_SIZE to prevent CPU spikes.
  • Async Handling: For high-volume batches (1000+ docs), always use async: true in your /render request to avoid server timeouts.

โ ๐Ÿ“„ License

MIT License โ€” see LICENSEโ  for details.


Built with โค๏ธ by volumeeeโ 

Tag summary

Content type

Image

Digest

sha256:ec330fdfcโ€ฆ

Size

361.8 MB

Last updated

7 months ago

docker pull bagose/html-to-pdf-api