HTML to PDF API: cURL, JavaScript, PHP & Python Examples

The Apixies HTML to PDF API works with any language that can send an HTTP POST request. This guide provides ready-to-use code examples in cURL, JavaScript (Node.js), PHP, and Python. Each example sends an HTML string to the API and saves the returned binary PDF to a file. Copy the snippet for your stack, replace the API key, and you are up and running in minutes.

Quick reference

Before diving into the code, here is a summary of the endpoint:

Detail Value
URL POST https://apixies.io/api/v1/html-to-pdf
Auth X-API-Key header
Body html -- a URL-encoded HTML string
Response Binary PDF (application/pdf)

You can start testing immediately. Anonymous requests (no API key) are allowed at 20 requests per day. Register for a free account to get 75 requests per day -- no credit card required.

cURL

cURL is the fastest way to test from the command line. The --output flag writes the binary response directly to a file.

Basic example

curl -X POST https://apixies.io/api/v1/html-to-pdf \
  -H "X-API-Key: YOUR_API_KEY" \
  -d 'html=<h1>Hello from cURL</h1><p>This is a simple PDF.</p>' \
  --output simple.pdf

Open simple.pdf in any reader to verify the result.

Sending a full HTML document

For richer output, pass a complete HTML document with inline CSS. URL-encode the HTML or use cURL's --data-urlencode flag to handle special characters automatically:

curl -X POST https://apixies.io/api/v1/html-to-pdf \
  -H "X-API-Key: YOUR_API_KEY" \
  --data-urlencode 'html=<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <style>
    body { font-family: Georgia, serif; padding: 50px; color: #333; }
    h1 { color: #2c5282; }
    table { width: 100%; border-collapse: collapse; margin-top: 20px; }
    th, td { border: 1px solid #ccc; padding: 8px; text-align: left; }
    th { background: #edf2f7; }
  </style>
</head>
<body>
  <h1>Q1 Sales Summary</h1>
  <table>
    <tr><th>Month</th><th>Revenue</th></tr>
    <tr><td>January</td><td>$12,400</td></tr>
    <tr><td>February</td><td>$15,800</td></tr>
    <tr><td>March</td><td>$14,200</td></tr>
  </table>
</body>
</html>' \
  --output sales-report.pdf

The --data-urlencode flag is especially useful when your HTML contains characters like #, &, or + that would otherwise break the POST body.

JavaScript (Node.js)

Modern Node.js (18+) includes the global fetch API, so no external packages are needed. This example uses URLSearchParams to handle encoding and writes the PDF with the built-in fs module.

const fs = require('fs');

async function generatePdf() {
  const html = `
    <!DOCTYPE html>
    <html>
    <head>
      <style>
        body { font-family: 'Segoe UI', sans-serif; padding: 40px; }
        .header { color: #2b6cb0; border-bottom: 3px solid #2b6cb0; padding-bottom: 8px; }
        .content { margin-top: 20px; line-height: 1.8; color: #4a5568; }
      </style>
    </head>
    <body>
      <h1 class="header">Project Status Report</h1>
      <div class="content">
        <p><strong>Sprint:</strong> 14</p>
        <p><strong>Velocity:</strong> 42 points</p>
        <p><strong>Blockers:</strong> None</p>
        <p>All deliverables are on track for the March milestone.</p>
      </div>
    </body>
    </html>`;

  const response = await fetch('https://apixies.io/api/v1/html-to-pdf', {
    method: 'POST',
    headers: {
      'X-API-Key': process.env.APIXIES_KEY,
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: new URLSearchParams({ html }),
  });

  if (!response.ok) {
    const error = await response.text();
    throw new Error(`API error ${response.status}: ${error}`);
  }

  const buffer = Buffer.from(await response.arrayBuffer());
  fs.writeFileSync('status-report.pdf', buffer);
  console.log('Saved status-report.pdf');
}

generatePdf();

Tip: streaming to an Express response

If you are building a web app and want to let users download a PDF directly, you can pipe the API response to the Express response object instead of saving to disk:

app.get('/download-report', async (req, res) => {
  const response = await fetch('https://apixies.io/api/v1/html-to-pdf', {
    method: 'POST',
    headers: {
      'X-API-Key': process.env.APIXIES_KEY,
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: new URLSearchParams({ html: buildReportHtml(req.query) }),
  });

  res.setHeader('Content-Type', 'application/pdf');
  res.setHeader('Content-Disposition', 'attachment; filename="report.pdf"');
  const buffer = Buffer.from(await response.arrayBuffer());
  res.send(buffer);
});

PHP

PHP's built-in cURL extension handles the request. The response body is saved directly to a file with file_put_contents.

<?php

$apiKey = getenv('APIXIES_KEY');

$html = '<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: Arial, sans-serif; padding: 40px; }
    h1 { color: #2d3748; }
    .highlight { background: #fefcbf; padding: 10px; border-left: 4px solid #d69e2e; }
  </style>
</head>
<body>
  <h1>Shipping Confirmation</h1>
  <p>Your order <strong>#90821</strong> has been shipped.</p>
  <div class="highlight">
    <p>Tracking number: <strong>1Z999AA10123456784</strong></p>
    <p>Estimated delivery: March 5, 2026</p>
  </div>
</body>
</html>';

$ch = curl_init('https://apixies.io/api/v1/html-to-pdf');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "X-API-Key: {$apiKey}",
    'Content-Type: application/x-www-form-urlencoded',
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(['html' => $html]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$pdf = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($statusCode === 200) {
    file_put_contents('shipping-confirmation.pdf', $pdf);
    echo "Saved shipping-confirmation.pdf\n";
} else {
    echo "Error ({$statusCode}): {$pdf}\n";
}

Tip: returning the PDF as a download in Laravel

In a Laravel controller, you can return the PDF binary directly as a download response:

return response($pdf, 200, [
    'Content-Type' => 'application/pdf',
    'Content-Disposition' => 'attachment; filename="confirmation.pdf"',
]);

Python

Python's requests library makes the call straightforward. The response content is raw bytes, which you write to a file in binary mode.

import requests
import os

api_key = os.environ["APIXIES_KEY"]

html = """<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: 'Courier New', monospace; padding: 40px; }
    h1 { color: #553c9a; }
    pre { background: #f7fafc; padding: 16px; border: 1px solid #e2e8f0; overflow-x: auto; }
  </style>
</head>
<body>
  <h1>API Response Log</h1>
  <p>Captured at: 2026-02-20 14:32:00 UTC</p>
  <pre>{
  "status": "healthy",
  "uptime": "99.98%",
  "active_connections": 142
}</pre>
</body>
</html>"""

response = requests.post(
    "https://apixies.io/api/v1/html-to-pdf",
    headers={"X-API-Key": api_key},
    data={"html": html},
)
response.raise_for_status()

with open("api-log.pdf", "wb") as f:
    f.write(response.content)

print("Saved api-log.pdf")

Tip: generating PDFs in Django or Flask

In a Django view, return the binary content with the correct MIME type:

from django.http import HttpResponse

def download_pdf(request):
    html = render_to_string("report_template.html", context)
    response = requests.post(
        "https://apixies.io/api/v1/html-to-pdf",
        headers={"X-API-Key": settings.APIXIES_KEY},
        data={"html": html},
    )
    return HttpResponse(
        response.content,
        content_type="application/pdf",
        headers={"Content-Disposition": 'attachment; filename="report.pdf"'},
    )

Error handling across all languages

The API returns standard HTTP status codes. When the request succeeds, you get a 200 response with Content-Type: application/pdf. If something goes wrong, the response body will be JSON with an error message. Common scenarios:

  • 400 -- The html parameter is missing or empty.
  • 401 -- The API key is invalid or missing.
  • 429 -- You have exceeded your daily request limit.
  • 500 -- A server-side rendering error occurred.

Always check the HTTP status code before writing the response body to a .pdf file. In production, log the error response body so you can debug issues quickly.

Next steps

These examples cover the most common integration patterns. For a deeper tutorial on how the API works and why it beats self-hosted tools, read the HTML to PDF REST API guide. If you want to see a real-world use case, the invoice generation guide walks through building a dynamic PDF invoice from scratch.

Browse all available tutorials on the guides page, or dive into the full API documentation for parameter details and advanced options.

Get your free API key -- 75 requests per day, no credit card required.

Try the HTML to PDF Converter API

Free tier is for development & small projects. 75 requests/day with a registered account.

Getting Started

Explore

Resources

Get Started Free

Free for development and small projects.

Get Free API Key