# Invertir las páginas de un PDF

Invierta el orden de las páginas de un PDF para que la última pase a ser la primera.

Invierta el orden de las páginas de un PDF, de modo que la última pase a ser
la primera y la primera pase a ser la última. La API es *stateless*: su
documento se procesa en la región y nunca se almacena.

<Tip>
  Para reorganizar las páginas en un orden arbitrario, y no solo invertirlas
  por completo, use [Reordenar páginas](/docs/api/reorder-pages-of-pdf).
</Tip>

## Endpoint

<Endpoint method="POST" path="/v1/reverse_pages" />

Disponible en todas las regiones. Consulte [Regiones y residencia de
datos](/docs/api/regions-and-data-residency) para el enrutamiento y la
residencia de datos.

| Región           | URL                                                 |
| ---------------- | --------------------------------------------------- |
| Global           | `https://api.pdfblocks.com/v1/reverse_pages`        |
| Estados Unidos   | `https://us.api.pdfblocks.com/v1/reverse_pages`     |
| HIPAA de EE. UU. | `https://hipaa.api.pdfblocks.com/v1/reverse_pages`  |
| Unión Europea    | `https://eu.api.pdfblocks.com/v1/reverse_pages`     |
| Reino Unido      | `https://uk.api.pdfblocks.com/v1/reverse_pages`     |
| Canadá           | `https://ca.api.pdfblocks.com/v1/reverse_pages`     |
| Australia        | `https://au.api.pdfblocks.com/v1/reverse_pages`     |
| Japón            | `https://jp.api.pdfblocks.com/v1/reverse_pages`     |
| India            | `https://in.api.pdfblocks.com/v1/reverse_pages`     |
| Brasil           | `https://br.api.pdfblocks.com/v1/reverse_pages`     |

## Autenticación

Autentique cada solicitud con su clave de API secreta en la cabecera
`X-API-Key`, por HTTPS. Cree y administre sus claves desde el
[dashboard](https://dashboard.pdfblocks.com). Consulte
[Autenticación](/docs/api/authentication) para más detalles.

## Solicitud

El endpoint acepta un cuerpo de solicitud `multipart/form-data`.

<ParamField name="file" type="file" required>
  El documento PDF de entrada.
</ParamField>

## Ejemplos

Invierta el orden de las páginas de un PDF:

<CodeGroup>

```bash title="cURL"
curl https://api.pdfblocks.com/v1/reverse_pages \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -o reversed.pdf
```

```python title="Python"
# pip install requests
import requests

with open('input.pdf', 'rb') as file:
    response = requests.post(
        'https://api.pdfblocks.com/v1/reverse_pages',
        headers={'X-API-Key': 'your_api_key'},
        files={'file': file},
    )

response.raise_for_status()
with open('reversed.pdf', 'wb') as output:
    output.write(response.content)
```

```javascript title="Node.js"
// Node.js 18+
import { readFile, writeFile } from 'node:fs/promises';

const body = new FormData();
body.set('file', new Blob([await readFile('input.pdf')]), 'input.pdf');

const response = await fetch('https://api.pdfblocks.com/v1/reverse_pages', {
  method: 'POST',
  headers: { 'X-API-Key': 'your_api_key' },
  body,
});

if (!response.ok) throw new Error(`Request failed: ${response.status}`);
await writeFile('reversed.pdf', Buffer.from(await response.arrayBuffer()));
```

```php title="PHP"
<?php
$ch = curl_init('https://api.pdfblocks.com/v1/reverse_pages');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['X-API-Key: your_api_key'],
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => [
        'file' => new CURLFile('input.pdf', 'application/pdf'),
    ],
]);

$pdf = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200) {
    file_put_contents('reversed.pdf', $pdf);
}
```

```ruby title="Ruby"
# gem install http
require 'http'

response = HTTP
  .headers('X-API-Key' => 'your_api_key')
  .post('https://api.pdfblocks.com/v1/reverse_pages', form: {
    file: HTTP::FormData::File.new('input.pdf'),
  })

File.write('reversed.pdf', response.body) if response.status.success?
```

```go title="Go"
package main

import (
	"bytes"
	"io"
	"mime/multipart"
	"net/http"
	"os"
)

func main() {
	var buf bytes.Buffer
	form := multipart.NewWriter(&buf)

	file, _ := os.Open("input.pdf")
	defer file.Close()
	part, _ := form.CreateFormFile("file", "input.pdf")
	io.Copy(part, file)

	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/reverse_pages", &buf)
	req.Header.Set("Content-Type", form.FormDataContentType())
	req.Header.Set("X-API-Key", "your_api_key")

	res, _ := http.DefaultClient.Do(req)
	defer res.Body.Close()

	out, _ := os.Create("reversed.pdf")
	defer out.Close()
	io.Copy(out, res.Body)
}
```

```csharp title="C#"
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", "your_api_key");

using var form = new MultipartFormDataContent
{
    { new ByteArrayContent(File.ReadAllBytes("input.pdf")), "file", "input.pdf" },
};

var response = await client.PostAsync(
    "https://api.pdfblocks.com/v1/reverse_pages", form);
response.EnsureSuccessStatusCode();
await File.WriteAllBytesAsync(
    "reversed.pdf", await response.Content.ReadAsByteArrayAsync());
```

</CodeGroup>

## Respuesta

Si todo va bien, la respuesta es `200 OK` con el PDF invertido como cuerpo:

```http
HTTP/1.1 200 OK
Content-Type: application/pdf
Content-Length: 48213
```

La salida conserva el contenido y las dimensiones de todas las páginas: lo
único que se invierte es su orden. Escriba el cuerpo directamente en un
archivo, como hacen los ejemplos anteriores; en nuestro lado no se almacena
nada.

## Errores

Las solicitudes fallidas devuelven un cuerpo `application/problem+json`. El
error más habitual en este endpoint es un `400`, que se devuelve cuando `file` no
es un PDF legible: el objeto `errors` nombra cada campo:

```json
{
  "type": "https://www.pdfblocks.com/docs/api/v1/error/400",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "errors": {
    "file": ["Could not parse the PDF document. The file may be invalid or corrupt."]
  }
}
```

Una `X-API-Key` ausente o no válida devuelve un `401`. Consulte
[Errores](/docs/api/errors) para ver todos los códigos de estado y la forma
completa de la respuesta.

## Acciones relacionadas

<CardGroup cols={2}>

<Card title="Reordenar páginas" href="/docs/api/reorder-pages-of-pdf">
  Cualquier orden, no solo la inversión.
</Card>

<Card title="Girar páginas" href="/docs/api/rotate-pages-in-pdf">
  Gire las páginas un ángulo fijo.
</Card>

<Card title="Extraer páginas" href="/docs/api/extract-pages-from-pdf">
  Extraiga un subconjunto de páginas.
</Card>

<Card title="Quitar páginas" href="/docs/api/remove-pages-from-pdf">
  Descarte páginas del documento.
</Card>

</CardGroup>
