March 30, 2026

PDF API Quickstart: Node.js, Python & PHP — 5-Line Examples

quickstartNode.jsPythonPHPPDF API

Generate PDFs from HTML with a few dozen lines of code. This guide walks you through the FUNBREW PDF API with step-by-step examples in Node.js, Python, and PHP (plus Ruby and Go). If you're migrating from Puppeteer or Playwright, see the Puppeteer migration guide.

Setup

1. Create an Account

Sign up for free. The Free plan includes 30 PDF generations per month.

2. Get Your API Key

Navigate to the "API Keys" section in your dashboard and generate a key. It starts with sk-.

# Set as an environment variable (recommended)
export FUNBREW_PDF_API_KEY="sk-your-api-key"

For secure key management practices, see the security guide.

3. API Endpoint and Flow

POST https://pdf.funbrew.cloud/api/pdf/generate-from-html
Authorization: Bearer <API key>

Generating a PDF takes two steps:

  1. Send html and options as JSON. The API returns JSON shaped like {"success": true, "data": {"filename": ..., "download_url": ...}} (not the PDF itself)
  2. GET data.download_url (https://pdf.funbrew.cloud/api/pdf/download/<filename>) with the same API key to receive the PDF (Content-Type: application/pdf)

options accepts page-size (A3 / A4 / A5 / Letter / Legal), orientation (Portrait / Landscape, capitalized), margin-top / margin-right / margin-bottom / margin-left (mm, 0 to 50), and engine (fast / quality). Every example below follows these two steps.

Node.js

For TypeScript projects, see the TypeScript PDF API guide for type-safe implementations. For Next.js or Nuxt integrations, check the Next.js/Nuxt guide. For production Express, AWS Lambda, and edge-runtime patterns (concurrency, error handling, no Puppeteer required), see the Node PDF API Guide.

fetch (Built-in API)

Since Node.js 18, fetch is available globally (experimental in Node.js 18). No extra packages needed.

const fs = require('fs');

const API_BASE = 'https://pdf.funbrew.cloud';
const authHeaders = { Authorization: `Bearer ${process.env.FUNBREW_PDF_API_KEY}` };

async function generatePdf() {
  // 1. Generate: returns JSON with a download URL
  const response = await fetch(`${API_BASE}/api/pdf/generate-from-html`, {
    method: 'POST',
    headers: {
      ...authHeaders,
      'Content-Type': 'application/json',
      Accept: 'application/json',
    },
    body: JSON.stringify({
      html: `
        <html>
          <head>
            <style>
              body { font-family: Arial, sans-serif; padding: 40px; }
              h1 { color: #1a1a1a; border-bottom: 2px solid #3b82f6; padding-bottom: 8px; }
              .info { color: #6b7280; margin-top: 24px; }
            </style>
          </head>
          <body>
            <h1>Report</h1>
            <p>This PDF was generated via the API.</p>
            <p class="info">Generated at: ${new Date().toISOString()}</p>
          </body>
        </html>
      `,
      options: { 'page-size': 'A4' },
    }),
  });

  const result = await response.json();
  if (!response.ok || !result.success) {
    throw new Error(`API error ${response.status}: ${result.message}`);
  }

  // 2. Download: fetch the PDF with the same API key
  const pdfResponse = await fetch(result.data.download_url, { headers: authHeaders });
  if (!pdfResponse.ok) {
    throw new Error(`Download error: ${pdfResponse.status}`);
  }

  fs.writeFileSync('output.pdf', Buffer.from(await pdfResponse.arrayBuffer()));
  console.log('PDF generated: output.pdf');
}

generatePdf().catch((error) => {
  console.error(error);
  process.exit(1);
});

axios

With axios, keep the generation response as JSON and set responseType: 'arraybuffer' only for the download.

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

const headers = { Authorization: `Bearer ${process.env.FUNBREW_PDF_API_KEY}` };

async function generatePdf() {
  // 1. Generate (JSON)
  const { data: result } = await axios.post(
    'https://pdf.funbrew.cloud/api/pdf/generate-from-html',
    {
      html: '<h1>Hello PDF</h1><p>Generated with axios</p>',
      options: { 'page-size': 'A4', engine: 'fast' },
    },
    { headers }
  );

  // 2. Download (binary)
  const { data: pdf } = await axios.get(result.data.download_url, {
    headers,
    responseType: 'arraybuffer', // receive the PDF as binary
  });

  fs.writeFileSync('output.pdf', pdf);
  console.log('PDF generated: output.pdf');
}

generatePdf().catch((error) => {
  console.error(error.response?.data ?? error);
  process.exit(1);
});

Python

For Django or FastAPI integrations, see the Django/FastAPI PDF API guide. For a comparison of ReportLab, WeasyPrint, and other Python PDF libraries against the API approach, see the Python PDF Generation Guide.

requests

A widely used HTTP library in Python.

import os
import requests

API_BASE = 'https://pdf.funbrew.cloud'
HEADERS = {'Authorization': f'Bearer {os.environ["FUNBREW_PDF_API_KEY"]}'}

def generate_pdf():
    # 1. Generate: returns JSON with a download URL
    response = requests.post(
        f'{API_BASE}/api/pdf/generate-from-html',
        headers={**HEADERS, 'Accept': 'application/json'},
        json={
            'html': '''
                <html>
                <head>
                    <style>
                        body { font-family: Arial, sans-serif; padding: 40px; }
                        h1 { color: #1a1a1a; }
                        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
                        th, td { border: 1px solid #e5e7eb; padding: 12px; text-align: left; }
                        th { background: #f8fafc; }
                    </style>
                </head>
                <body>
                    <h1>Sales Report</h1>
                    <table>
                        <tr><th>Month</th><th>Revenue</th></tr>
                        <tr><td>January</td><td>$12,000</td></tr>
                        <tr><td>February</td><td>$13,500</td></tr>
                        <tr><td>March</td><td>$15,000</td></tr>
                    </table>
                </body>
                </html>
            ''',
            'options': {'page-size': 'A4'},
        },
        timeout=60,
    )
    response.raise_for_status()
    download_url = response.json()['data']['download_url']

    # 2. Download: fetch the PDF with the same API key
    pdf = requests.get(download_url, headers=HEADERS, timeout=60)
    pdf.raise_for_status()

    with open('report.pdf', 'wb') as f:
        f.write(pdf.content)
    print(f'PDF generated: report.pdf ({len(pdf.content)} bytes)')

generate_pdf()

httpx (Async Support)

For async workflows, httpx is a great choice.

import asyncio
import os

import httpx

HEADERS = {'Authorization': f'Bearer {os.environ["FUNBREW_PDF_API_KEY"]}'}

async def generate_pdf():
    async with httpx.AsyncClient(base_url='https://pdf.funbrew.cloud', timeout=60) as client:
        # 1. Generate (JSON)
        response = await client.post(
            '/api/pdf/generate-from-html',
            headers={**HEADERS, 'Accept': 'application/json'},
            json={
                'html': '<h1>Async PDF</h1><p>Generated with httpx</p>',
                'options': {'page-size': 'A4', 'engine': 'fast'},
            },
        )
        response.raise_for_status()
        download_url = response.json()['data']['download_url']

        # 2. Download (binary)
        pdf = await client.get(download_url, headers=HEADERS)
        pdf.raise_for_status()

    with open('output.pdf', 'wb') as f:
        f.write(pdf.content)
    print('PDF generated: output.pdf')

asyncio.run(generate_pdf())

PHP

For Ruby or Go code examples, see the Ruby/Go quickstart guide. For deeper Laravel patterns — service classes, Blade templates, queue jobs, and Http::fake() testing — see the Laravel PDF API Guide.

Laravel (Http Facade)

A concise approach using Laravel's built-in HTTP client.

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;

$apiKey = config('services.funbrew.api_key');

// 1. Generate: returns JSON with a download URL
$response = Http::withToken($apiKey)
    ->acceptJson()
    ->timeout(60)
    ->post('https://pdf.funbrew.cloud/api/pdf/generate-from-html', [
        'html' => '
            <html>
            <head>
                <style>
                    body { font-family: Arial, sans-serif; padding: 40px; }
                    h1 { color: #1a1a1a; }
                </style>
            </head>
            <body>
                <h1>Delivery Note</h1>
                <p>To: Acme Corp</p>
                <p>Total: $3,300.00 (incl. tax)</p>
            </body>
            </html>
        ',
        'options' => ['page-size' => 'A4'],
    ])
    ->throw();

// 2. Download: fetch the PDF with the same API key
$pdf = Http::withToken($apiKey)
    ->timeout(60)
    ->get($response->json('data.download_url'))
    ->throw();

Storage::put('pdfs/delivery-note.pdf', $pdf->body());

cURL (Framework-agnostic)

Plain PHP with cURL — works anywhere.

<?php

$apiKey = getenv('FUNBREW_PDF_API_KEY');

function funbrewRequest(string $url, string $apiKey, ?array $body = null): array
{
    $ch = curl_init($url);
    $headers = ['Authorization: Bearer ' . $apiKey];

    if ($body !== null) {
        $headers[] = 'Content-Type: application/json';
        $headers[] = 'Accept: application/json';
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
    }

    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_TIMEOUT => 60,
    ]);

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

    return [$httpCode, $responseBody];
}

// 1. Generate (JSON)
[$httpCode, $json] = funbrewRequest(
    'https://pdf.funbrew.cloud/api/pdf/generate-from-html',
    $apiKey,
    [
        'html' => '<h1>Hello PDF</h1>',
        'options' => ['page-size' => 'A4', 'engine' => 'fast'],
    ]
);

if ($httpCode !== 200) {
    exit("Error {$httpCode}: {$json}\n");
}

$result = json_decode($json, true);

// 2. Download (binary)
[$httpCode, $pdf] = funbrewRequest($result['data']['download_url'], $apiKey);

if ($httpCode === 200) {
    file_put_contents('output.pdf', $pdf);
}

Ruby

Use Ruby's standard library or the Faraday gem. There is no official Ruby or Go SDK, so these examples call the API directly with an HTTP client. For Rails service objects, Sidekiq async jobs, and production deployment patterns, see the PDF API in Ruby Guide.

net/http (Standard Library)

require 'net/http'
require 'json'
require 'uri'

api_key = ENV.fetch('FUNBREW_PDF_API_KEY')

# 1. Generate: returns JSON with a download URL
uri = URI('https://pdf.funbrew.cloud/api/pdf/generate-from-html')
request = Net::HTTP::Post.new(uri)
request['Authorization'] = "Bearer #{api_key}"
request['Content-Type'] = 'application/json'
request['Accept'] = 'application/json'
request.body = {
  html: '<h1>Hello from Ruby</h1><p>PDF generated with net/http</p>',
  options: { 'page-size' => 'A4', 'engine' => 'fast' }
}.to_json

response = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(request) }
abort "Error: #{response.code} - #{response.body}" unless response.is_a?(Net::HTTPSuccess)

download_url = JSON.parse(response.body).dig('data', 'download_url')

# 2. Download: fetch the PDF with the same API key
download_uri = URI(download_url)
download_request = Net::HTTP::Get.new(download_uri)
download_request['Authorization'] = "Bearer #{api_key}"

pdf = Net::HTTP.start(download_uri.host, download_uri.port, use_ssl: true) { |http| http.request(download_request) }
abort "Download error: #{pdf.code}" unless pdf.is_a?(Net::HTTPSuccess)

File.binwrite('output.pdf', pdf.body)
puts "PDF generated: output.pdf (#{pdf.body.bytesize} bytes)"

Faraday

Faraday's json request and response middleware encode the request body and parse JSON responses for you.

require 'faraday'

conn = Faraday.new(url: 'https://pdf.funbrew.cloud') do |f|
  f.request :json          # send Hash bodies as JSON
  f.response :json         # parse JSON responses into a Hash (PDF is left as is)
  f.response :raise_error  # raise on 4xx / 5xx
  f.headers['Authorization'] = "Bearer #{ENV.fetch('FUNBREW_PDF_API_KEY')}"
  f.headers['Accept'] = 'application/json'
end

# 1. Generate (JSON)
response = conn.post('/api/pdf/generate-from-html', {
  html: '<h1>Hello from Ruby</h1><p>PDF generated with Faraday</p>',
  options: { 'page-size' => 'A4' }
})

# 2. Download (binary)
pdf = conn.get(response.body.dig('data', 'download_url'))
File.binwrite('output.pdf', pdf.body)

Go

Go's standard library is all you need — no external dependencies (there is no official Go SDK). For a production-grade guide covering goroutine worker pools, exponential backoff retry logic, and Gin/Echo integration, see the Go PDF API Guide.

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"time"
)

type generateResponse struct {
	Success bool   `json:"success"`
	Message string `json:"message"`
	Data    struct {
		Filename    string `json:"filename"`
		DownloadURL string `json:"download_url"`
	} `json:"data"`
}

func main() {
	apiKey := os.Getenv("FUNBREW_PDF_API_KEY")
	client := &http.Client{Timeout: 60 * time.Second}

	payload, err := json.Marshal(map[string]any{
		"html": "<h1>Hello from Go</h1><p>PDF generated with net/http</p>",
		"options": map[string]any{
			"page-size": "A4",
			"engine":    "fast",
		},
	})
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(1)
	}

	// 1. Generate: returns JSON with a download URL
	req, err := http.NewRequest(http.MethodPost,
		"https://pdf.funbrew.cloud/api/pdf/generate-from-html",
		bytes.NewReader(payload))
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(1)
	}
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Accept", "application/json")

	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(1)
	}
	defer resp.Body.Close()

	var result generateResponse
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		fmt.Println("Error:", err)
		os.Exit(1)
	}
	if resp.StatusCode != http.StatusOK || !result.Success {
		fmt.Printf("Error %d: %s\n", resp.StatusCode, result.Message)
		os.Exit(1)
	}

	// 2. Download: fetch the PDF with the same API key
	dlReq, err := http.NewRequest(http.MethodGet, result.Data.DownloadURL, nil)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(1)
	}
	dlReq.Header.Set("Authorization", "Bearer "+apiKey)

	dlResp, err := client.Do(dlReq)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(1)
	}
	defer dlResp.Body.Close()

	pdf, err := io.ReadAll(dlResp.Body)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(1)
	}
	if dlResp.StatusCode != http.StatusOK {
		fmt.Printf("Download error %d: %s\n", dlResp.StatusCode, pdf)
		os.Exit(1)
	}

	if err := os.WriteFile("output.pdf", pdf, 0o644); err != nil {
		fmt.Println("Error:", err)
		os.Exit(1)
	}
	fmt.Printf("PDF generated: output.pdf (%d bytes)\n", len(pdf))
}

Error Handling

Always check the HTTP status code. Errors come back as JSON shaped like {"success": false, "message": "..."}. The main status codes and what to do about them are below. For more error-handling patterns, see the PDF API Error Handling Guide.

Status Meaning What to do
401 Authentication error (missing or invalid API key) Check the API key and the Authorization: Bearer header
403 Not allowed (a feature your plan lacks, e.g. engine: quality on Free, or the key's scope / IP restriction) Check your plan and key settings. Do not retry
422 Validation error (empty html, out-of-range options value, etc.) Fix the request based on errors. Do not retry
429 Limit exceeded (per-minute request limit, or monthly generation / storage limit) Only the per-minute 429 carries a Retry-After header (seconds); wait that long and retry. The monthly and storage 429s do not clear by waiting, so review your plan
500 Generation failed Note the X-Job-Id header and retry later

Timeouts matter too. Generation time depends on the HTML and on any external resources it loads, so avoid very short timeouts and measure with your real HTML before deciding (the examples above use 60 seconds).

Choosing an Engine

FUNBREW PDF offers two rendering engines, selectable per request with options.engine. If you omit it, your company's default setting and plan decide.

Engine Parameter Under the hood Plans
Fast "options": {"engine": "fast"} wkhtmltopdf All plans
Quality "options": {"engine": "quality"} Chromium (Gotenberg) Pro and above (403 on Free)

Quality falls back to Fast (wkhtmltopdf) when Gotenberg is not configured on the server. If your layout relies on modern CSS such as CSS Grid, check the actual PDF output. For technical details on engine differences, see wkhtmltopdf vs Chromium.

Frequently Asked Questions

Can I use external CSS or web fonts in HTML?

You can send HTML that references external stylesheets or web fonts with <link> tags, but the generation server must be able to fetch them, and loading them adds to generation time. For production, prefer inline styles and self-hosted fonts, and check the output PDF to confirm fonts and layout render as intended. Fonts can differ by engine, so check non-Latin text (such as Japanese) in the actual PDF in particular.

Base64 or URL for images?

Embedding small icons and logos as Base64 data URIs removes the dependency on an external image server. It also makes the HTML larger, and html has a length limit (5,000,000 characters by default), so use URL references for large images to keep requests small. URL-referenced images must be at a public URL the generation server can fetch.

How can I reduce PDF file size?

Start with the HTML: keep image resolution no higher than needed and avoid loading unused web fonts. File size can vary by engine, so if it matters, render the same HTML with fast and quality and compare.

Next Steps

Once you have basic PDF generation working, explore these features:

Related

Powered by FUNBREW PDF