Documentation API

Tout ce dont vous avez besoin pour intégrer WebPDF.app dans vos projets.

Pour Commencer

WebPDF.app propose une API REST simple pour convertir HTML en PDF. Suivez ces étapes pour commencer en moins de 5 minutes.

1

Créer un compte

Inscrivez-vous gratuitement pour accéder au tableau de bord.

2

Générer une clé API

Depuis le tableau de bord, allez dans "API Keys" et créez une nouvelle clé.

3

Faire votre première requête

Utilisez votre clé API pour authentifier les requêtes vers l'endpoint /v1/generate.

Démarrage rapide - cURL
curl -X POST https://api.webpdf.app/v1/generate \
  -H "Content-Type: application/json" \
  -d '{"apiKey": "YOUR_API_KEY", "url": "https://example.com"}' \
  --output document.pdf

Authentification

Toutes les requêtes API doivent inclure votre clé API dans le corps de la requête JSON.

Authentification par clé API

Incluez le champ apiKey dans le corps de votre requête JSON.

En-têtes de Requête
{
  "apiKey": "wpdf_live_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6",
  "url": "https://example.com"
}

Endpoint /generate

POST https://api.webpdf.app/v1/generate

Convertit une page web ou un contenu HTML en document PDF.

Corps de la requête (JSON)

Paramètre Type Description
apiKey string Clé API per l'authentification
url string URL de la page web à convertir. Requis si html n'est pas fourni.
html string Contenu HTML direct à convertir. Requis si url n'est pas fourni.
format string Format de page : "Letter", "Legal", "Tabloid", "Ledger", "A0", "A1", "A2", "A3", "A4", "A5", "A6" (défaut : "A4")
landscape boolean Orientation : true pour paysage, false pour portrait (défaut : false)
marginTop entier Marge haute en pixels (défaut : 0)
marginRight entier Marge droite en pixels (défaut : 0)
marginBottom entier Marge basse en pixels (défaut : 0)
marginLeft entier Marge gauche en pixels (défaut : 0)
width entier Largeur personnalisée en pixels (écrase le format)
height entier Hauteur personnalisée en pixels (écrase le format)
media string Type de média CSS : "screen" ou "print" (défaut : "screen")
Exemple de Requête
{
  "apiKey": "your-api-key-here",
  "url": "https://example.com",
  "format": "A4",
  "landscape": false,
  "marginTop": 10,
  "marginRight": 10,
  "marginBottom": 10,
  "marginLeft": 10,
  "media": "print"
}

Paramètres Disponibles

Les paramètres suivants peuvent être envoyés dans le corps JSON de votre requête POST.

Paramètre docs.options.type Défaut docs.options.description
format string "A4" Format de page (Letter, Legal, Tabloid, Ledger, A0-A6)
width string - Largeur personnalisée en pixels (écrase le format)
height string - Hauteur personnalisée en pixels (écrase le format)
landscape boolean false Orientation : true pour paysage, false pour portrait
margin object 0 Marges (marginTop, marginRight, marginBottom, marginLeft)
printBackground boolean true Type de média CSS : "screen" ou "print"
scale entier 1 Note : Au moins un des paramètres url ou html doit être fourni. Si les deux sont fournis, html est utilisé.
displayHeaderFooter boolean false Afficher l'en-tête et le pied de page
headerTemplate string - Template HTML pour l'en-tête
footerTemplate string - Template HTML pour le pied de page
pageRanges string - Pages à inclure (ex: "1-5, 8")
waitForSelector string - Sélecteur CSS à attendre avant le rendu
waitForTimeout entier 0 Millisecondes d'attente supplémentaires

Exemples de Code

Copiez et collez ces exemples pour commencer rapidement dans votre langage préféré.

// Node.js / JavaScript
const generatePdf = async () => {
  const response = await fetch('https://api.webpdf.app/v1/generate', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      apiKey: process.env.WEBPDF_API_KEY,
      url: 'https://example.com',
      format: 'A4',
      landscape: false
    })
  });

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

  const pdfBuffer = await response.arrayBuffer();
  return Buffer.from(pdfBuffer);
};

// Usage
const pdf = await generatePdf();
fs.writeFileSync('output.pdf', pdf);
# Python
import requests
import os

def generate_pdf(url_to_convert):
    api_url = "https://api.webpdf.app/v1/generate"
    payload = {
        "apiKey": os.environ.get('WEBPDF_API_KEY'),
        "url": url_to_convert,
        "format": "A4",
        "landscape": False
    }
    headers = {"Content-Type": "application/json"}
    
    response = requests.post(api_url, json=payload, headers=headers)
    
    if response.status_code == 200:
        return response.content
    else:
        print(f"Errore: {response.status_code} - {response.text}")
        return None

# Usage
pdf_bytes = generate_pdf("https://example.com")
if pdf_bytes:
    with open("output.pdf", "wb") as f:
        f.write(pdf_bytes)
// PHP
<?php

function generatePdf($url) {
    $apiKey = getenv('WEBPDF_API_KEY');
    
    $data = [
        'apiKey' => $apiKey,
        'url' => $url,
        'format' => 'A4',
        'landscape' => false
    ];
    
    $ch = curl_init('https://api.webpdf.app/v1/generate');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($data),
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json'
        ]
    ]);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    return $response;
}

// Usage
$pdf = generatePdf('https://example.com');
file_put_contents('output.pdf', $pdf);
// Java (with HttpClient)
import java.net.http.*;
import java.net.URI;

public class WebPdfClient {
    private static final String API_URL = "https://api.webpdf.app/v1/generate";
    private final String apiKey;
    
    public WebPdfClient(String apiKey) {
        this.apiKey = apiKey;
    }
    
    public byte[] generatePdf(String url) throws Exception {
        String json = String.format("{\"apiKey\":\"%s\",\"url\":\"%s\",\"format\":\"A4\"}", apiKey, url);
        
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(API_URL))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(json))
            .build();
        
        HttpResponse response = client.send(
            request, HttpResponse.BodyHandlers.ofByteArray()
        );
        
        return response.body();
    }
}
// C# (.NET)
using System.Net.Http;
using System.Text;
using System.Text.Json;

public class WebPdfClient
{
    private readonly HttpClient _client;
    private readonly string _apiKey;
    private const string ApiUrl = "https://api.webpdf.app/v1/generate";

    public WebPdfClient(string apiKey)
    {
        _client = new HttpClient();
        _apiKey = apiKey;
    }

    public async Task<byte[]> GeneratePdfAsync(string url)
    {
        var payload = new {
            apiKey = _apiKey,
            url = url,
            format = "A4"
        };

        var json = JsonSerializer.Serialize(payload);
        var content = new StringContent(json, Encoding.UTF8, "application/json");

        var response = await _client.PostAsync(ApiUrl, content);
        response.EnsureSuccessStatusCode();

        return await response.Content.ReadAsByteArrayAsync();
    }
}
# cURL con URL
curl -X POST https://api.webpdf.app/v1/generate \
  -H "Content-Type: application/json" \
  -d '{
    "apiKey": "test-key",
    "url": "https://example.com",
    "format": "A4",
    "landscape": false
  }' \
  --output document.pdf

# cURL con HTML diretto
curl -X POST https://api.webpdf.app/v1/generate \
  -H "Content-Type: application/json" \
  -d '{
    "apiKey": "test-key",
    "html": "

Test

PDF generato da HTML.

", "format": "A4" }'
\ --output document.pdf

Gestion des Erreurs

L'API renvoie des codes HTTP standards et un corps JSON avec les détails de l'erreur.

Code Signification Action
200 Succès PDF généré avec succès
400 Mauvaise Requête Vérifiez les paramètres de la requête
401 Non Autorisé Clé API manquante ou invalide
403 Interdit Crédits insuffisants ou compte suspendu
429 Trop de Requêtes Limite de débit dépassée, réessayez plus tard
500 Erreur Serveur Erreur interne, contactez-nous se cela persiste

Limites de Débit

Pour garantir la stabilité du service, nous appliquons des limites de requête par clé API.

Limites par forfait

  • Gratuit 60 req/min
  • Startup 300 req/min
  • Business 600 req/min
  • Entreprise Custom

En-têtes de réponse

  • X-RateLimit-Limit: Limite de requêtes par fenêtre
  • X-RateLimit-Remaining: Requêtes restantes
  • X-RateLimit-Reset: Horodatage de réinitialisation de la limite

Journal des modifications

v3.0.0 - Janvier 2024

Mise à jour des fonctionnalités

  • Ajout du support pour le paramètre html
  • Le paramètre url devient conditionnel
  • Validation améliorée per les paramètres requis
  • Maintien de la rétrocompatibilité

v1.1.0 - Juin 2023

Sortie Initiale

  • Endpoint initial /v1/generate
  • Conversion HTML en PDF con iText 7
  • Récupération automatique du contenu web
  • Nettoyage HTML avec Jsoup
  • Support pour les PDF existants

v1.0.0 - Jun 2023