html4pdf

Code Examples

Complete, production-ready examples in multiple programming languages.

Basic HTML to PDF

generate-pdf.js
const fetch = require('node-fetch');
const fs = require('fs');

async function generatePDF() {
  const response = await fetch('https://api.html4pdf.com/generate-pdf', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      html: `
        <html>
          <head>
            <style>
              body { font-family: Arial; padding: 40px; }
              h1 { color: #2563eb; }
            </style>
          </head>
          <body>
            <h1>Invoice #001</h1>
            <p>Total: $500.00</p>
          </body>
        </html>
      `,
      options: {
        format: 'A4',
        margin: { top: '20mm', right: '15mm', bottom: '20mm', left: '15mm' }
      }
    })
  });

  const data = await response.json();
  const pdfBuffer = Buffer.from(data.pdf, 'base64');
  fs.writeFileSync('invoice.pdf', pdfBuffer);

  console.log(`PDF generated! Credits remaining: ${data.creditsRemaining}`);
}

generatePDF();
generate_pdf.py
import requests
import base64

def generate_pdf():
    response = requests.post(
        'https://api.html4pdf.com/generate-pdf',
        headers={
            'Authorization': 'Bearer YOUR_API_KEY',
            'Content-Type': 'application/json'
        },
        json={
            'html': '''
                <html>
                    <head>
                        <style>
                            body { font-family: Arial; padding: 40px; }
                            h1 { color: #2563eb; }
                        </style>
                    </head>
                    <body>
                        <h1>Invoice #001</h1>
                        <p>Total: $500.00</p>
                    </body>
                </html>
            ''',
            'options': {
                'format': 'A4',
                'margin': {
                    'top': '20mm',
                    'right': '15mm',
                    'bottom': '20mm',
                    'left': '15mm'
                }
            }
        }
    )

    data = response.json()
    pdf_bytes = base64.b64decode(data['pdf'])

    with open('invoice.pdf', 'wb') as f:
        f.write(pdf_bytes)

    print(f"PDF generated! Credits remaining: {data['creditsRemaining']}")

if __name__ == '__main__':
    generate_pdf()
generate-pdf.php
<?php

function generatePDF() {
    $apiKey = 'YOUR_API_KEY';
    $url = 'https://api.html4pdf.com/generate-pdf';

    $html = '
        <html>
            <head>
                <style>
                    body { font-family: Arial; padding: 40px; }
                    h1 { color: #2563eb; }
                </style>
            </head>
            <body>
                <h1>Invoice #001</h1>
                <p>Total: $500.00</p>
            </body>
        </html>
    ';

    $data = json_encode([
        'html' => $html,
        'options' => [
            'format' => 'A4',
            'margin' => [
                'top' => '20mm',
                'right' => '15mm',
                'bottom' => '20mm',
                'left' => '15mm'
            ]
        ]
    ]);

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $apiKey,
        'Content-Type: application/json'
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode === 200) {
        $result = json_decode($response, true);
        $pdfData = base64_decode($result['pdf']);
        file_put_contents('invoice.pdf', $pdfData);

        echo "PDF generated! Credits remaining: " . $result['creditsRemaining'] . "\n";
    }
}

generatePDF();
?>
generate_pdf.rb
require 'net/http'
require 'uri'
require 'json'
require 'base64'

def generate_pdf
  uri = URI.parse('https://api.html4pdf.com/generate-pdf')

  request = Net::HTTP::Post.new(uri)
  request['Authorization'] = 'Bearer YOUR_API_KEY'
  request['Content-Type'] = 'application/json'

  request.body = {
    html: '<html><head><style>body { font-family: Arial; padding: 40px; } h1 { color: #2563eb; }</style></head><body><h1>Invoice #001</h1><p>Total: $500.00</p></body></html>',
    options: {
      format: 'A4',
      margin: {
        top: '20mm',
        right: '15mm',
        bottom: '20mm',
        left: '15mm'
      }
    }
  }.to_json

  response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
    http.request(request)
  end

  if response.is_a?(Net::HTTPSuccess)
    data = JSON.parse(response.body)
    pdf_data = Base64.decode64(data['pdf'])

    File.open('invoice.pdf', 'wb') { |file| file.write(pdf_data) }
    puts "PDF generated! Credits remaining: #{data['creditsRemaining']}"
  end
end

generate_pdf
main.go
package main

import (
    "bytes"
    "encoding/base64"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

type PDFRequest struct {
    HTML    string     `json:"html"`
    Options PDFOptions `json:"options"`
}

type PDFOptions struct {
    Format string `json:"format"`
    Margin Margin `json:"margin"`
}

type Margin struct {
    Top    string `json:"top"`
    Right  string `json:"right"`
    Bottom string `json:"bottom"`
    Left   string `json:"left"`
}

type PDFResponse struct {
    Success          bool   `json:"success"`
    PDF              string `json:"pdf"`
    CreditsRemaining int    `json:"creditsRemaining"`
}

func main() {
    apiKey := "YOUR_API_KEY"
    url := "https://api.html4pdf.com/generate-pdf"

    reqBody := PDFRequest{
        HTML: "<html><head><style>body{font-family:Arial;padding:40px;}h1{color:#2563eb;}</style></head><body><h1>Invoice #001</h1><p>Total: $500.00</p></body></html>",
        Options: PDFOptions{
            Format: "A4",
            Margin: Margin{Top: "20mm", Right: "15mm", Bottom: "20mm", Left: "15mm"},
        },
    }

    jsonData, _ := json.Marshal(reqBody)
    req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
    req.Header.Set("Authorization", "Bearer "+apiKey)
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, _ := client.Do(req)
    defer resp.Body.Close()

    body, _ := ioutil.ReadAll(resp.Body)
    var pdfResp PDFResponse
    json.Unmarshal(body, &pdfResp)

    pdfData, _ := base64.StdEncoding.DecodeString(pdfResp.PDF)
    ioutil.WriteFile("invoice.pdf", pdfData, 0644)

    fmt.Printf("PDF generated! Credits remaining: %d\n", pdfResp.CreditsRemaining)
}
generate-pdf.sh
curl -X POST https://api.html4pdf.com/generate-pdf \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "html": "<html><head><style>body{font-family:Arial;padding:40px;}h1{color:#2563eb;}</style></head><body><h1>Invoice #001</h1><p>Total: $500.00</p></body></html>",
    "options": {
      "format": "A4",
      "margin": {
        "top": "20mm",
        "right": "15mm",
        "bottom": "20mm",
        "left": "15mm"
      }
    }
  }' | jq -r '.pdf' | base64 -d > invoice.pdf

Binary Response (Faster)

binary-response.js
async function generateBinaryPDF() {
  const response = await fetch('https://api.html4pdf.com/generate-pdf', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      html: '<h1>Hello World</h1>',
      responseFormat: 'binary'
    })
  });

  // Get metadata from headers
  const creditsCharged = response.headers.get('X-Credits-Charged');
  const creditsRemaining = response.headers.get('X-Credits-Remaining');

  console.log(`Credits charged: ${creditsCharged}`);
  console.log(`Credits remaining: ${creditsRemaining}`);

  // Save binary PDF
  const arrayBuffer = await response.arrayBuffer();
  const buffer = Buffer.from(arrayBuffer);
  fs.writeFileSync('document.pdf', buffer);
}

generateBinaryPDF();
binary_response.py
def generate_binary_pdf():
    response = requests.post(
        'https://api.html4pdf.com/generate-pdf',
        headers={
            'Authorization': 'Bearer YOUR_API_KEY',
            'Content-Type': 'application/json'
        },
        json={
            'html': '<h1>Hello World</h1>',
            'responseFormat': 'binary'
        }
    )

    # Get metadata from headers
    credits_charged = response.headers.get('X-Credits-Charged')
    credits_remaining = response.headers.get('X-Credits-Remaining')

    print(f"Credits charged: {credits_charged}")
    print(f"Credits remaining: {credits_remaining}")

    # Save binary PDF directly
    with open('document.pdf', 'wb') as f:
        f.write(response.content)

generate_binary_pdf()
binary-response.sh
curl -X POST https://api.html4pdf.com/generate-pdf \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "html": "<h1>Hello World</h1>",
    "responseFormat": "binary"
  }' -o document.pdf -D headers.txt

# View response headers
cat headers.txt | grep "X-Credits"

Using Templates

Invoice Template

generate-invoice.js
async function generateInvoice() {
  const response = await fetch('https://api.html4pdf.com/generate-pdf', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      template: {
        type: 'invoice',
        data: {
          company: {
            name: 'ACME Corporation',
            email: '[email protected]',
            phone: '+1 (555) 123-4567'
          },
          client: {
            name: 'Client Company Inc',
            email: '[email protected]'
          },
          invoice: {
            number: 'INV-2024-001',
            date: 'January 15, 2024',
            dueDate: 'February 15, 2024'
          },
          items: [
            {
              description: 'Web Development Services',
              quantity: 40,
              rate: 150.00,
              amount: 6000.00
            }
          ],
          subtotal: 6000.00,
          tax: 600.00,
          total: 6600.00,
          notes: 'Payment due within 30 days.'
        },
        theme: {
          primaryColor: '#2563eb'
        }
      }
    })
  });

  const data = await response.json();
  const pdfBuffer = Buffer.from(data.pdf, 'base64');
  fs.writeFileSync('invoice.pdf', pdfBuffer);

  console.log('Invoice generated!');
}

generateInvoice();
generate_invoice.py
def generate_invoice():
    response = requests.post(
        'https://api.html4pdf.com/generate-pdf',
        headers={
            'Authorization': 'Bearer YOUR_API_KEY',
            'Content-Type': 'application/json'
        },
        json={
            'template': {
                'type': 'invoice',
                'data': {
                    'company': {
                        'name': 'ACME Corporation',
                        'email': '[email protected]',
                        'phone': '+1 (555) 123-4567'
                    },
                    'client': {
                        'name': 'Client Company Inc',
                        'email': '[email protected]'
                    },
                    'invoice': {
                        'number': 'INV-2024-001',
                        'date': 'January 15, 2024',
                        'dueDate': 'February 15, 2024'
                    },
                    'items': [
                        {
                            'description': 'Web Development Services',
                            'quantity': 40,
                            'rate': 150.00,
                            'amount': 6000.00
                        }
                    ],
                    'subtotal': 6000.00,
                    'tax': 600.00,
                    'total': 6600.00,
                    'notes': 'Payment due within 30 days.'
                },
                'theme': {
                    'primaryColor': '#2563eb'
                }
            }
        }
    )

    data = response.json()
    pdf_bytes = base64.b64decode(data['pdf'])

    with open('invoice.pdf', 'wb') as f:
        f.write(pdf_bytes)

    print('Invoice generated!')

generate_invoice()
generate-invoice.php
<?php

function generateInvoice() {
    $apiKey = 'YOUR_API_KEY';
    $url = 'https://api.html4pdf.com/generate-pdf';

    $data = json_encode([
        'template' => [
            'type' => 'invoice',
            'data' => [
                'company' => [
                    'name' => 'ACME Corporation',
                    'email' => '[email protected]',
                    'phone' => '+1 (555) 123-4567'
                ],
                'client' => [
                    'name' => 'Client Company Inc',
                    'email' => '[email protected]'
                ],
                'invoice' => [
                    'number' => 'INV-2024-001',
                    'date' => 'January 15, 2024',
                    'dueDate' => 'February 15, 2024'
                ],
                'items' => [
                    [
                        'description' => 'Web Development Services',
                        'quantity' => 40,
                        'rate' => 150.00,
                        'amount' => 6000.00
                    ]
                ],
                'subtotal' => 6000.00,
                'tax' => 600.00,
                'total' => 6600.00,
                'notes' => 'Payment due within 30 days.'
            ],
            'theme' => [
                'primaryColor' => '#2563eb'
            ]
        ]
    ]);

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $apiKey,
        'Content-Type: application/json'
    ]);

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

    $result = json_decode($response, true);
    $pdfData = base64_decode($result['pdf']);
    file_put_contents('invoice.pdf', $pdfData);

    echo "Invoice generated!\n";
}

generateInvoice();
?>

Next Steps