Documentación API
Todo lo que necesitas para integrar WebPDF.app en tus proyectos.
Para Comenzar
WebPDF.app ofrece una API REST simple para convertir HTML a PDF. Sigue estos pasos para comenzar en menos de 5 minutos.
Crea una cuenta
Regístrate gratis para obtener acceso al panel de control.
Genera una Clave API
Desde el panel de control, ve a "Claves API" y crea una nueva clave.
Haz tu primera solicitud
Usa tu Clave API para autenticar solicitudes al 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
Autenticación
Todas las solicitudes API deben incluir tu Clave API en el cuerpo de la solicitud JSON.
Autenticación con Clave API
Incluye el campo apiKey en el cuerpo JSON de tu solicitud. Nota: Actualmente, todas las claves son aceptadas para fines de prueba.
{
"apiKey": "wpdf_live_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6",
"url": "https://example.com"
}
Endpoint /generate
https://api.webpdf.app/v1/generate
Convierte una página web o contenido HTML en un documento PDF.
Cuerpo de Solicitud (JSON)
| Parámetro | Tipo | Descripción |
|---|---|---|
apiKey |
string | Clave API para autenticación (actualmente no validada) |
url |
string | URL de la página web a convertir. Requerido si no se proporciona html. |
html |
string | Contenido HTML directo para convertir. Requerido si no se proporciona url. |
format |
string | Formato de página: "Letter", "Legal", "Tabloid", "Ledger", "A0", "A1", "A2", "A3", "A4", "A5", "A6" (predeterminado: "A4") |
landscape |
boolean | Orientación de página: true para horizontal, false para vertical (predeterminado: false) |
marginTop |
integer | Margen superior en píxeles (predeterminado: 0) |
marginRight |
integer | Margen derecho en píxeles (predeterminado: 0) |
marginBottom |
integer | Margen inferior en píxeles (predeterminado: 0) |
marginLeft |
integer | Margen izquierdo en píxeles (predeterminado: 0) |
width |
integer | Ancho personalizado de página en píxeles (anula format) |
height |
integer | Alto personalizado de página en píxeles (anula format) |
media |
string | Tipo de Media CSS: "screen" o "print" (predeterminado: "screen") |
{
"apiKey": "your-api-key-here",
"url": "https://example.com",
"format": "A4",
"landscape": false,
"marginTop": 10,
"marginRight": 10,
"marginBottom": 10,
"marginLeft": 10,
"media": "print"
}
Parámetros Disponibles
Los siguientes parámetros pueden enviarse en el cuerpo JSON de tu solicitud POST.
| Parámetro | docs.options.type | Predeterminado | docs.options.description |
|---|---|---|---|
format |
string | "A4" | Formato de página (Letter, Legal, Tabloid, Ledger, A0-A6) |
width |
string | - | Ancho personalizado en píxeles (anula format) |
height |
string | - | Alto personalizado en píxeles (anula format) |
landscape |
boolean | false | Orientación: true para horizontal, false para vertical |
margin |
object | 0 | Márgenes (marginTop, marginRight, marginBottom, marginLeft) |
printBackground |
boolean | true | Tipo de Media CSS: "screen" o "print" |
scale |
integer | 1 | Nota: Se debe proporcionar al menos uno entre url o html. Si se proporcionan ambos, se usa html. |
displayHeaderFooter |
boolean | false | Mostrar encabezado y pie de página |
headerTemplate |
string | - | Plantilla HTML para encabezado |
footerTemplate |
string | - | Plantilla HTML para pie de página |
pageRanges |
string | - | Páginas a incluir (ej. "1-5, 8") |
waitForSelector |
string | - | Selector CSS para esperar antes de renderizar |
waitForTimeout |
integer | 0 | Milisegundos adicionales para esperar |
Ejemplos de Código
Copia y pega estos ejemplos para comenzar rápidamente en tu lenguaje preferido.
// 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
Manejo de Errores
La API devuelve códigos HTTP estándar y un cuerpo JSON con detalles del error.
| Código | Significado | Acción |
|---|---|---|
| 200 | Éxito | PDF generado correctamente |
| 400 | Solicitud Incorrecta | Verifica los parámetros de la solicitud |
| 401 | No Autorizado | Clave API faltante o no válida |
| 403 | Prohibido | Créditos insuficientes o cuenta suspendida |
| 429 | Demasiadas Solicitudes | Límite de tasa excedido, intenta más tarde |
| 500 | Error del Servidor | Error interno, contáctanos si persiste |
Límites de Tasa
Para garantizar la estabilidad del servicio, aplicamos límites de solicitudes por Clave API.
Límites por plan
- Gratis 60 req/min
- Startup 300 req/min
- Business 600 req/min
- Enterprise Custom
Encabezados de respuesta
X-RateLimit-Limit: Límite de solicitudes por ventanaX-RateLimit-Remaining: Solicitudes restantesX-RateLimit-Reset: Marca de tiempo de reinicio del límite
Registro de Cambios
v3.0.0 - Enero 2024
Actualización de Características
- Agregado soporte para parámetro html
- Parámetro url se vuelve condicional
- Validación mejorada para parámetros obligatorios
- Mantenida compatibilidad con versiones anteriores
v1.1.0 - Junio 2023
Lanzamiento Inicial
- Endpoint inicial /v1/generate
- Conversión HTML a PDF con iText 7
- Obtención automática de contenido web
- Limpieza HTML con Jsoup
- Soporte para PDF ya existentes (pass-through)