# Girar páginas de un PDF

Gire las páginas seleccionadas de un PDF un ángulo fijo, en el sentido de las agujas del reloj o en el contrario.

Gire las páginas de un documento PDF un ángulo fijo. Los ángulos positivos
giran en el sentido de las agujas del reloj y los negativos en el sentido
contrario. De forma predeterminada se giran todas las páginas: use el
parámetro [`pages`](#seleccionar-páginas) para apuntar a un subconjunto. La API
es *stateless*: su documento se procesa en la región y nunca se almacena.

## Endpoint

<Endpoint method="POST" path="/v1/rotate_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/rotate_pages`       |
| Estados Unidos   | `https://us.api.pdfblocks.com/v1/rotate_pages`    |
| HIPAA de EE. UU. | `https://hipaa.api.pdfblocks.com/v1/rotate_pages` |
| Unión Europea    | `https://eu.api.pdfblocks.com/v1/rotate_pages`    |
| Reino Unido      | `https://uk.api.pdfblocks.com/v1/rotate_pages`    |
| Canadá           | `https://ca.api.pdfblocks.com/v1/rotate_pages`    |
| Australia        | `https://au.api.pdfblocks.com/v1/rotate_pages`    |
| Japón            | `https://jp.api.pdfblocks.com/v1/rotate_pages`    |
| India            | `https://in.api.pdfblocks.com/v1/rotate_pages`    |
| Brasil           | `https://br.api.pdfblocks.com/v1/rotate_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>

<ParamField name="angle" type="integer" required>
  El giro que se aplicará, en grados. Uno de [los ángulos
  válidos](#ángulos-de-giro). Los valores positivos giran en el sentido de
  las agujas del reloj y los negativos en el sentido contrario.
</ParamField>

<ParamField name="pages" type="string">
  Las páginas que se girarán, escritas como un [rango de
  páginas](#seleccionar-páginas) tipo `1..3,5`. Si se omite, se giran todas las
  páginas. Máximo 1000 caracteres.
</ParamField>

### Ángulos de giro

Pase uno de los valores siguientes al parámetro `angle`.

| Ángulo  | Giro                                                                                  |
| ------- | ------------------------------------------------------------------------------------- |
| `0`     | Sin giro                                                                              |
| `90`    | 90° en el sentido de las agujas del reloj                                             |
| `180`   | 180°                                                                                  |
| `270`   | 270° en el sentido de las agujas del reloj (90° en el sentido contrario)              |
| `-90`   | 90° en el sentido contrario a las agujas del reloj                                    |
| `-180`  | 180°                                                                                  |
| `-270`  | 270° en el sentido contrario a las agujas del reloj (90° en el sentido de las agujas) |

Los ángulos positivos giran en el sentido de las agujas del reloj y los
negativos en el sentido contrario; cada giro se suma al giro actual de la
página.

### Seleccionar páginas

El parámetro `pages` recibe una lista separada por comas de números de página
en base 1 y de rangos. Se trata como un **conjunto**: el orden y los
duplicados se ignoran, y las páginas siempre se giran en el orden del
documento.

| Patrón     | Selecciona                                 |
| ---------- | ------------------------------------------ |
| *(omitir)* | Todas las páginas                          |
| `1`        | Solo la primera página                     |
| `1..3,5`   | Las páginas 1, 2, 3 y 5                    |
| `2..`      | De la página 2 a la última                 |
| `..-2`     | De la primera página a la penúltima        |
| `-1`       | La última página                           |

Consulte [Seleccionar páginas](/docs/api/selecting-pages) para ver la
referencia completa.

## Ejemplos

Gire las tres primeras páginas 90° en el sentido de las agujas del reloj:

<CodeGroup>

```bash title="cURL"
curl https://api.pdfblocks.com/v1/rotate_pages \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F angle=90 \
  -F pages='1..3' \
  -o rotated.pdf
```

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

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

response.raise_for_status()
with open('rotated.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');
body.set('angle', '90');
body.set('pages', '1..3');

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

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

```php title="PHP"
<?php
$ch = curl_init('https://api.pdfblocks.com/v1/rotate_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'),
        'angle' => '90',
        'pages' => '1..3',
    ],
]);

$pdf = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200) {
    file_put_contents('rotated.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/rotate_pages', form: {
    file: HTTP::FormData::File.new('input.pdf'),
    angle: '90',
    pages: '1..3',
  })

File.write('rotated.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.WriteField("angle", "90")
	form.WriteField("pages", "1..3")
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/rotate_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("rotated.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" },
    { new StringContent("90"), "angle" },
    { new StringContent("1..3"), "pages" },
};

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

</CodeGroup>

## Respuesta

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

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

La salida conserva las mismas páginas y el mismo contenido que la entrada: lo
único que cambia es el giro de las páginas seleccionadas. 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 `angle` no
es uno de los valores admitidos o `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": {
    "angle": ["The angle must be one of 0, 90, 180, 270, -90, -180, -270."]
  }
}
```

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.

## Recetas

Variantes habituales. Despliegue una para verla en todos los lenguajes.

<AccordionGroup>

<Accordion title="Poner derecho un escaneo horizontal">

<CodeGroup>

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

```python title="Python"
import requests

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

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

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

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

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

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

```php title="PHP"
<?php
$ch = curl_init('https://api.pdfblocks.com/v1/rotate_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'),
        'angle' => '90',
    ],
]);

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

```ruby title="Ruby"
require 'http'

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

File.write('upright.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.WriteField("angle", "90")
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/rotate_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("upright.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" },
    { new StringContent("90"), "angle" },
};

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

</CodeGroup>

</Accordion>

<Accordion title="Girar todas las páginas 180°">

<CodeGroup>

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

```python title="Python"
import requests

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

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

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

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

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

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

```php title="PHP"
<?php
$ch = curl_init('https://api.pdfblocks.com/v1/rotate_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'),
        'angle' => '180',
    ],
]);

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

```ruby title="Ruby"
require 'http'

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

File.write('flipped.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.WriteField("angle", "180")
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/rotate_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("flipped.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" },
    { new StringContent("180"), "angle" },
};

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

</CodeGroup>

</Accordion>

</AccordionGroup>

## Acciones relacionadas

<CardGroup cols={2}>

<Card title="Invertir páginas" href="/docs/api/reverse-pages-of-pdf">
  Invierta el orden de las páginas.
</Card>

<Card title="Reordenar páginas" href="/docs/api/reorder-pages-of-pdf">
  Reorganice las páginas en cualquier orden.
</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>
