Documentazione API
Tutto ciò che ti serve per integrare WebPDF.app nei tuoi progetti.
Per Iniziare
WebPDF.app offre un'API REST semplice per convertire HTML in PDF. Segui questi passaggi per iniziare in meno di 5 minuti.
Crea un account
Registrati gratuitamente per ottenere accesso alla dashboard.
Genera una API Key
Dalla dashboard, vai su "API Keys" e crea una nuova chiave.
Fai la tua prima richiesta
Usa la tua API Key per autenticare le richieste all'endpoint /v1/generate.
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
Autenticazione
Tutte le richieste API devono includere la tua API Key nel corpo della richiesta JSON.
Autenticazione tramite API Key
Includi il campo apiKey nel corpo JSON della richiesta. Nota: Attualmente tutte le chiavi sono accettate per scopi di test.
{
"apiKey": "wpdf_live_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6",
"url": "https://example.com"
}
Endpoint /generate
https://api.webpdf.app/v1/generate
Converte una pagina web o contenuto HTML in un documento PDF.
Corpo della Richiesta (JSON)
| Parametro | Tipo | Descrizione |
|---|---|---|
apiKey |
string | Chiave API per l'autenticazione (attualmente non validata) |
url |
string | URL della pagina web da convertire. Obbligatorio se html non è fornito. |
html |
string | Contenuto HTML diretto da convertire. Obbligatorio se url non è fornito. |
format |
string | Formato della pagina: "Letter", "Legal", "Tabloid", "Ledger", "A0", "A1", "A2", "A3", "A4", "A5", "A6" (default: "A4") |
landscape |
boolean | Orientamento della pagina: true per orizzontale, false per verticale (default: false) |
marginTop |
integer | Margine superiore in pixel (default: 0) |
marginRight |
integer | Margine destro in pixel (default: 0) |
marginBottom |
integer | Margine inferiore in pixel (default: 0) |
marginLeft |
integer | Margine sinistro in pixel (default: 0) |
width |
integer | Larghezza personalizzata della pagina in pixel (sovrascrive format) |
height |
integer | Altezza personalizzata della pagina in pixel (sovrascrive format) |
media |
string | Tipo di media CSS: "screen" o "print" (default: "screen") |
{
"apiKey": "your-api-key-here",
"url": "https://example.com",
"format": "A4",
"landscape": false,
"marginTop": 10,
"marginRight": 10,
"marginBottom": 10,
"marginLeft": 10,
"media": "print"
}
Parametri Disponibili
I seguenti parametri possono essere inviati nel corpo JSON della richiesta POST.
| Parametro | docs.options.type | Default | docs.options.description |
|---|---|---|---|
format |
string | "A4" | Formato pagina (Letter, Legal, Tabloid, Ledger, A0-A6) |
width |
string | - | Larghezza custom in pixel (sovrascrive format) |
height |
string | - | Altezza custom in pixel (sovrascrive format) |
landscape |
boolean | false | Orientamento: true per orizzontale, false per verticale |
margin |
object | 0 | Margini (marginTop, marginRight, marginBottom, marginLeft) |
printBackground |
boolean | true | Tipo media CSS: "screen" o "print" |
scale |
integer | 1 | Nota: È obbligatorio fornire almeno uno tra url e html. Se vengono forniti entrambi, viene usato html. |
displayHeaderFooter |
boolean | false | Mostra header e footer |
headerTemplate |
string | - | Template HTML per header |
footerTemplate |
string | - | Template HTML per footer |
pageRanges |
string | - | Pagine da includere (es. "1-5, 8") |
waitForSelector |
string | - | Selector CSS da attendere prima del render |
waitForTimeout |
integer | 0 | Millisecondi di attesa aggiuntivi |
Esempi Codice
Copia e incolla questi esempi per iniziare rapidamente nel tuo linguaggio preferito.
// 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
Gestione Errori
L'API restituisce codici HTTP standard e un body JSON con dettagli dell'errore.
| Codice | Significato | Azione |
|---|---|---|
| 200 | Successo | PDF generato correttamente |
| 400 | Bad Request | Verifica i parametri della richiesta |
| 401 | Unauthorized | API Key mancante o non valida |
| 403 | Forbidden | Crediti esauriti o account sospeso |
| 429 | Too Many Requests | Rate limit superato, riprova dopo |
| 500 | Server Error | Errore interno, contattaci se persiste |
Rate Limits
Per garantire stabilità del servizio, applichiamo limiti alle richieste per API Key.
Limiti per piano
- Free 60 req/min
- Startup 300 req/min
- Business 600 req/min
- Enterprise Custom
Headers di risposta
X-RateLimit-Limit: Limite richieste per finestraX-RateLimit-Remaining: Richieste rimanentiX-RateLimit-Reset: Timestamp reset limite
Changelog
v3.0.0 - Gennaio 2024
Feature Update
- Aggiunto supporto per parametro html
- Parametro url diventa condizionale
- Validazione migliorata per i parametri obbligatori
- Mantenuta retrocompatibilità con le richieste esistenti
v1.1.0 - Giugno 2023
Release Iniziale
- Endpoint iniziale /v1/generate
- Conversione HTML to PDF con iText 7
- Fetch automatico di contenuti web
- Pulizia HTML con Jsoup
- Supporto per PDF già esistenti (pass-through)