PDFLayer.pro API Documentation

Complete guide to integrating our HTML to PDF conversion API into your applications.

🎉 New users get 50 free credits every month - no credit card required!

Getting Started

99.9%
Uptime SLA
<500ms
Avg Response
250/min
Rate Limit

Base URL

https://pdflayer.pro/api

Quick Test

Test the API immediately with this simple curl command:

curl -X POST https://pdflayer.pro/api/convert-auth \
  -H "Content-Type: application/json" \
  -H "X-API-Key: YOUR_API_KEY" \
  -d '{"source": "<h1>Hello World!</h1>"}' \
  --output test.pdf

Authentication

All API requests require authentication using your API key in the request header.

Required Header
X-API-Key: pk_your_api_key_here

⚠️ Security Warning: Never expose your API key in client-side code. Always make requests from your server backend.

Rate Limits

  • Authenticated: 250 requests per minute
  • Per API Key: No daily limits
  • Burst: Up to 50 concurrent requests

Sandbox Mode

We highly recommend using sandbox mode during development. When enabled, sandbox mode adds a watermark to your generated PDF but doesn't consume your credits, allowing unlimited testing.

💡 Pro Tip: Always use sandbox=true during development and testing. Only disable it for final production conversions.

Sandbox Request

{
  "source": "<h1>Test Document</h1>",
  "sandbox": true,
  "options": {
    "format": "A4"
  }
}

Sandbox Benefits

  • No Credit Cost: Test unlimited conversions for free
  • Same Quality: Identical output except for watermark
  • Full Features: All API options work in sandbox mode
  • Easy Toggle: Just add "sandbox": true to your request

Multiple API Keys

Manage multiple API keys for different applications or environments. Each account can have up to 10 API keys.

Creating API Keys

Create new API keys through your dashboard or via API:

curl -X POST https://pdflayer.pro/api/users/api-keys   -H "x-api-key: your_primary_key"   -H "Content-Type: application/json"   -d '{
    "name": "Production App",
    "description": "API key for production environment"
  }'

Using API Keys

All API keys work interchangeably for PDF conversion. Credits are shared across your account.

curl -X POST https://pdflayer.pro/api/convert-auth   -H "x-api-key: your_api_key_here"   -H "Content-Type: application/json"   -d '{
    "source": "<html><body><h1>Hello World</h1></body></html>",
    "options": { "format": "A4" }
  }'

💡 Tip: Use different API keys for development, staging, and production environments to track usage patterns.

Cookies Support

Pass cookies when converting URLs that require authentication or session data.

{
  "url": "https://myapp.com/protected-page",
  "options": {
    "cookies": [
      {
        "name": "session_id",
        "value": "abc123xyz",
        "domain": "myapp.com",
        "secure": true,
        "http_only": true
      },
      {
        "name": "auth_token",
        "value": "bearer_token_here"
      }
    ]
  }
}

Cookie Parameters

ParameterTypeDescription
namestringCookie name (required)
valuestringCookie value (required)
domainstringCookie domain (optional, defaults to URL domain)
securebooleanHTTPS only cookie (optional)
http_onlybooleanHTTP-only cookie flag (optional)

Basic Authentication

Access password-protected URLs using HTTP Basic Authentication.

{
  "url": "https://myapp.com/protected-area",
  "options": {
    "auth": {
      "username": "admin",
      "password": "secret123"
    }
  }
}

🔒 Security: Basic auth credentials are transmitted securely and not stored. Use HTTPS URLs when possible.

Enhanced Response Headers

Our API returns detailed information about your PDF conversion in response headers.

Standard Headers

HeaderDescription
X-Credits-RemainingCredits left in your account
X-Credits-UsedCredits consumed by this conversion
X-File-SizeSize of generated PDF in bytes
X-Process-TimeProcessing time in milliseconds
X-Sandbox-ModeWhether sandbox mode was used
X-PDFLayer-ProcessorPDF rendering engine used
X-Request-IdUnique request identifier for support

Example Response

X-Credits-Remaining: 1234
X-Credits-Used: 1
X-File-Size: 52347
X-Process-Time: 1250
X-Sandbox-Mode: false
X-PDFLayer-Processor: chromium
X-Request-Id: req_1642684800_abc123

Convert HTML to PDF

POST /api/convert-auth

Convert HTML strings directly to PDF with full CSS support and custom styling options.

Basic Request

{
  "source": "<html><body><h1>Your Content</h1></body></html>",
  "options": {
    "format": "A4",
    "landscape": false
  }
}

Advanced HTML Example

{
  "source": "<!DOCTYPE html><html><head><style>body{font-family:Arial}</style></head><body><h1>Report</h1><p>Content here</p></body></html>",
  "options": {
    "format": "A4",
    "margin": {
      "top": "2cm",
      "bottom": "2cm",
      "left": "1.5cm",
      "right": "1.5cm"
    },
    "printBackground": true,
    "css": "h1 { color: #00ff88; }",
    "header": {
      "source": "<div style='text-align: center; font-size: 12px;'>{{title}} - Page {{page}}</div>",
      "height": "1cm"
    },
    "footer": {
      "source": "<div style='text-align: center; font-size: 10px;'>Generated on {{date}}</div>",
      "height": "1cm"
    }
  }
}

Convert URL to PDF

Convert any web page to PDF by providing a URL. Perfect for generating reports from dashboards, invoices from web apps, or archiving web content.

Basic URL Conversion

{
  "url": "https://myapp.com",
  "options": {
    "format": "A4",
    "delay": 2000
  }
}

Authenticated Pages

{
  "url": "https://app.myapp.com/dashboard",
  "options": {
    "format": "A4",
    "auth": {
      "username": "your_username",
      "password": "your_password"
    },
    "cookies": [
      {
        "name": "session_token",
        "value": "abc123xyz",
        "domain": "app.myapp.com"
      }
    ],
    "http_headers": {
      "Authorization": "Bearer your_token",
      "User-Agent": "PDFForge-Bot/1.0"
    },
    "delay": 3000,
    "wait_for": "dataLoaded"
  }
}

Advanced Options

Page Settings

formatA4, A3, Letter, Legal, Tabloid
landscapetrue/false - Page orientation
scale0.1-2.0 - Page zoom level
pages"1-3,5" - Select specific pages

Timing Controls

delayMilliseconds to wait before capture
timeoutMax seconds to load page
wait_forJS function name to wait for

Custom Styling

{
  "source": "<h1>Styled Document</h1>",
  "options": {
    "css": "h1 { color: #00ff88; font-size: 48px; }",
    "javascript": "document.title = 'Generated PDF';",
    "disable_javascript": false,
    "disable_backgrounds": false,
    "lazy_load_images": true
  }
}

Headers & Footers

Add custom headers and footers to your PDFs with dynamic content like page numbers, dates, and titles.

Available Variables

{{page}}

Current page number

{{totalPages}}

Total page count

{{date}}

Current date

{{title}}

Document title

Example

{
  "source": "<h1>Business Report</h1><p>Content...</p>",
  "options": {
    "header": {
      "source": "<div style='display: flex; justify-content: space-between; padding: 0 1cm; font-size: 12px;'><span>{{title}}</span><span>{{date}}</span></div>",
      "height": "1.5cm"
    },
    "footer": {
      "source": "<div style='text-align: center; font-size: 10px; color: #666;'>Page {{page}} of {{totalPages}}</div>",
      "height": "1cm"
    }
  }
}

Security & Protection

Protect your generated PDFs with passwords and usage restrictions.

PDF Protection

{
  "source": "<h1>Confidential Report</h1>",
  "options": {
    "protection": {
      "user_password": "user123",     // Password to open PDF
      "owner_password": "admin456",   // Password for editing
      "no_print": true,               // Disable printing
      "no_modify": true,              // Disable modifications
      "no_copy": true                 // Disable copying text
    }
  }
}

💡 Tip: PDF protection is not foolproof but adds a reasonable barrier for casual users. For highly sensitive documents, consider additional server-side restrictions.

HIPAA Compliance

PDFForge is HIPAA compliant and suitable for processing Protected Health Information (PHI). Enable HIPAA mode for healthcare applications.

HIPAA Mode Request

{
  "source": "<h1>Patient Report</h1><p>Sensitive medical data...</p>",
  "options": {
    "hipaa_compliant": true,
    "format": "A4",
    "protection": {
      "user_password": "secure_password",
      "no_print": true,
      "no_copy": true
    },
    "watermark": {
      "text": "CONFIDENTIAL - PHI",
      "opacity": 0.3
    }
  }
}

🔒 HIPAA Mode: Automatically enforces security requirements including HTTPS-only webhooks, encrypted storage, and disabled external script execution.

Security Features

  • • End-to-end encryption (AES-256)
  • • Secure memory handling
  • • Immediate temporary file deletion
  • • Comprehensive audit logging
  • • Business Associate Agreements available

Learn more about our HIPAA compliance →

Watermarks

Add text or image watermarks to your PDFs for branding or marking document status.

Text Watermark

{
  "source": "<h1>Document</h1>",
  "options": {
    "watermark": {
      "text": "CONFIDENTIAL",
      "opacity": 0.3,
      "position": "center",
      "rotation": 45,
      "font_size": 72,
      "color": "#ff0000"
    }
  }
}

Image Watermark

{
  "source": "<h1>Document</h1>",
  "options": {
    "watermark": {
      "image": "https://myapp.com/logo.png",
      "opacity": 0.2,
      "position": "top-right",
      "scale": 0.5
    }
  }
}

Available Positions

top-left
top-center
top-right
center-left
center
center-right
bottom-left
bottom-center
bottom-right

Webhooks

For large documents or batch processing, use webhooks to receive notifications when your PDF is ready for download.

Webhook Request

{
  "source": "<h1>Large Document</h1>",
  "options": {
    "webhook": "https://myapp.com/webhooks/pdf-ready",
    "format": "A4"
  }
}

Webhook Response (202)

{
  "success": true,
  "message": "PDF generation queued",
  "webhook": "https://myapp.com/webhooks/pdf-ready",
  "credits_remaining": 245
}

Webhook Payload

When PDF is ready, we'll POST to your webhook URL:

{
  "status": "success",
  "pdf_url": "https://pdflayer.pro/storage/generated.pdf",
  "original_request": { ... },
  "processing_time": 1247,
  "file_size": 2048576
}

Credits API

GET /api/users/credits

Check your current credit balance and view transaction history.

Request

curl https://pdflayer.pro/api/users/credits \
  -H "X-API-Key: pk_your_api_key"

Response

{
  "credits": 245,
  "history": [
    {
      "id": "crd_abc123",
      "amount": -1,
      "type": "usage",
      "description": "PDF conversion",
      "createdAt": "2024-01-15T10:30:00Z"
    },
    {
      "id": "crd_def456",
      "amount": 500,
      "type": "purchase",
      "description": "Purchased 500 credits",
      "createdAt": "2024-01-14T15:20:00Z"
    }
  ]
}

Error Handling

Our API uses conventional HTTP response codes to indicate success or failure.

200 - Success

PDF generated successfully

202 - Queued

PDF generation queued (webhook mode)

400 - Bad Request

Invalid parameters or missing required fields

401 - Unauthorized

Invalid or missing API key

402 - Insufficient Credits

Not enough credits to complete conversion

429 - Rate Limited

Too many requests - try again later

Code Examples

JavaScript/Node.js

const axios = require('axios');
const fs = require('fs');

async function convertToPDF() {
  try {
    const response = await axios.post('https://pdflayer.pro/api/convert-auth', {
      source: '<h1>Hello World</h1>',
      options: {
        format: 'A4',
        margin: { top: '1cm', bottom: '1cm' }
      }
    }, {
      headers: {
        'Content-Type': 'application/json',
        'X-API-Key': 'pk_your_api_key'
      },
      responseType: 'arraybuffer'
    });

    fs.writeFileSync('output.pdf', response.data);
    console.log('PDF saved successfully!');
  } catch (error) {
    console.error('Error:', error.response.data);
  }
}

Python

import requests

def convert_to_pdf():
    url = "https://pdflayer.pro/api/convert-auth"
    headers = {
        "Content-Type": "application/json",
        "X-API-Key": "pk_your_api_key"
    }
    data = {
        "source": "<h1>Hello World</h1>",
        "options": {
            "format": "A4",
            "watermark": {
                "text": "DRAFT",
                "opacity": 0.3
            }
        }
    }
    
    response = requests.post(url, json=data, headers=headers)
    
    if response.status_code == 200:
        with open("output.pdf", "wb") as f:
            f.write(response.content)
        print("PDF saved successfully!")
    else:
        print(f"Error: {response.json()}")

PHP

<?php
$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_URL => 'https://pdflayer.pro/api/convert-auth',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => array(
        'Content-Type: application/json',
        'X-API-Key: pk_your_api_key'
    ),
    CURLOPT_POSTFIELDS => json_encode(array(
        'source' => '<h1>Hello World</h1>',
        'options' => array(
            'format' => 'A4',
            'header' => array(
                'source' => '<div>Page {{page}}</div>',
                'height' => '1cm'
            )
        )
    ))
));

$response = curl_exec($curl);
curl_close($curl);

file_put_contents('output.pdf', $response);
echo "PDF saved successfully!";
?>

Ruby

require 'net/http'
require 'json'

uri = URI('https://pdflayer.pro/api/convert-auth')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

request = Net::HTTP::Post.new(uri)
request['Content-Type'] = 'application/json'
request['X-API-Key'] = 'pk_your_api_key'

request.body = {
  source: '<h1>Hello World</h1>',
  options: {
    format: 'A4',
    protection: {
      user_password: 'secret123'
    }
  }
}.to_json

response = http.request(request)

File.open('output.pdf', 'wb') do |file|
  file.write(response.body)
end

puts "PDF saved successfully!"