# Riordinare le pagine di un PDF

Riorganizzare le pagine di un PDF nell’ordine esatto che si indica: una ripetizione duplica una pagina, un’omissione la scarta.

Riorganizzare le pagine di un PDF in qualsiasi ordine tramite il parametro
[`page_order`](#ordine-delle-pagine). Poiché `page_order` usa [la sintassi
ordinata delle pagine](/docs/api/selecting-pages), questa azione funge anche da
estrazione e riordino combinati: le pagine omesse vengono scartate e una pagina
indicata due volte viene ripetuta. L’API è *stateless*: il documento viene
elaborato nella regione e non viene mai memorizzato.

## Endpoint

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

Disponibile in tutte le regioni. Vedere [Regioni e residenza dei
dati](/docs/api/regions-and-data-residency) per il routing e la residenza dei
dati.

| Regione            | URL                                                 |
| ------------------ | --------------------------------------------------- |
| Globale            | `https://api.pdfblocks.com/v1/reorder_pages`        |
| Stati Uniti        | `https://us.api.pdfblocks.com/v1/reorder_pages`     |
| HIPAA Stati Uniti  | `https://hipaa.api.pdfblocks.com/v1/reorder_pages`  |
| Unione europea     | `https://eu.api.pdfblocks.com/v1/reorder_pages`     |
| Regno Unito        | `https://uk.api.pdfblocks.com/v1/reorder_pages`     |
| Canada             | `https://ca.api.pdfblocks.com/v1/reorder_pages`     |
| Australia          | `https://au.api.pdfblocks.com/v1/reorder_pages`     |
| Giappone           | `https://jp.api.pdfblocks.com/v1/reorder_pages`     |
| India              | `https://in.api.pdfblocks.com/v1/reorder_pages`     |
| Brasile            | `https://br.api.pdfblocks.com/v1/reorder_pages`     |

## Autenticazione

Autenticare ogni richiesta con la chiave API segreta nell’intestazione
`X-API-Key`, tramite HTTPS. Le chiavi si creano e si gestiscono dalla
[dashboard](https://dashboard.pdfblocks.com). Vedere
[Autenticazione](/docs/api/authentication) per i dettagli.

## Richiesta

L’endpoint accetta un corpo della richiesta `multipart/form-data`.

<ParamField name="file" type="file" required>
  Il documento PDF di input.
</ParamField>

<ParamField name="page_order" type="string" required>
  L’ordine delle pagine desiderato, scritto con [la sintassi ordinata delle
  pagine](#ordine-delle-pagine), ad esempio `3,1,2`. Le pagine omesse vengono
  scartate e una pagina indicata più di una volta viene ripetuta. Massimo
  1000 caratteri.
</ParamField>

### Ordine delle pagine

`page_order` viene letto come un **elenco ordinato**, non come un insieme: le
pagine escono esattamente nell’ordine indicato. Una pagina indicata due volte
viene emessa due volte e qualsiasi pagina omessa viene scartata. Un intervallo
può anche procedere a ritroso: `10..5` va dalla pagina 10 alla pagina 5.

I numeri sono in base 1 e un indice negativo conta dalla fine: `-1` è quindi
l’ultima pagina.

| `page_order` | Produce                                             |
| ------------ | --------------------------------------------------- |
| `3,1,2`      | Le pagine 3, 1 e poi 2                              |
| `2..`        | Dalla pagina 2 all’ultima pagina, in ordine         |
| `-1,1..-2`   | L’ultima pagina, poi tutte quelle che la precedono  |
| `1,1,2..`    | La pagina 1 due volte, poi dalla pagina 2 in avanti |
| `10..5`      | Dalla pagina 10 alla 5, in ordine inverso           |

Vedere [Selezionare le pagine](/docs/api/selecting-pages) per il riferimento
completo, comprese le differenze tra il `page_order` ordinato e il campo
`pages`, che si basa su un insieme.

## Esempi

Mettere la pagina 3 per prima, poi le pagine 1 e 2:

<CodeGroup>

```bash title="cURL"
curl https://api.pdfblocks.com/v1/reorder_pages \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F page_order='3,1,2' \
  -o reordered.pdf
```

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

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

response.raise_for_status()
with open('reordered.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('page_order', '3,1,2');

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

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

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

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

File.write('reordered.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("page_order", "3,1,2")
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/reorder_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("reordered.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("3,1,2"), "page_order" },
};

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

</CodeGroup>

## Risposta

In caso di successo, la risposta è `200 OK` e il corpo contiene il PDF
riordinato:

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

Scrivere il corpo direttamente in un file, come fanno gli esempi qui sopra; non
viene memorizzato nulla dalla nostra parte.

## Errori

Le richieste non riuscite restituiscono un corpo `application/problem+json`.
L’errore più frequente su questo endpoint è un `400`, restituito quando
`page_order` è malformato o indica una pagina che il documento non contiene.
L’oggetto `errors` identifica il campo:

```json
{
  "type": "https://www.pdfblocks.com/docs/api/v1/error/400",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "errors": {
    "page_order": ["The page_order field references a page that does not exist in the document."]
  }
}
```

Una `X-API-Key` mancante o non valida restituisce un `401`. Vedere
[Errori](/docs/api/errors) per tutti i codici di stato e la forma completa della
risposta.

## Ricette

Varianti comuni. Espanderne una per vederla in tutti i linguaggi.

<AccordionGroup>

<Accordion title="Spostare l’ultima pagina all’inizio">

<CodeGroup>

```bash title="cURL"
curl https://api.pdfblocks.com/v1/reorder_pages \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F page_order='-1,1..-2' \
  -o last-first.pdf
```

```python title="Python"
import requests

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

response.raise_for_status()
with open('last-first.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('page_order', '-1,1..-2');

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

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

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

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

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

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

File.write('last-first.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("page_order", "-1,1..-2")
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/reorder_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("last-first.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("-1,1..-2"), "page_order" },
};

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

</CodeGroup>

</Accordion>

<Accordion title="Duplicare la pagina di copertina">

<CodeGroup>

```bash title="cURL"
curl https://api.pdfblocks.com/v1/reorder_pages \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F page_order='1,1..-1' \
  -o doubled-cover.pdf
```

```python title="Python"
import requests

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

response.raise_for_status()
with open('doubled-cover.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('page_order', '1,1..-1');

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

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

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

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

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

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

File.write('doubled-cover.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("page_order", "1,1..-1")
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/reorder_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("doubled-cover.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("1,1..-1"), "page_order" },
};

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

</CodeGroup>

</Accordion>

</AccordionGroup>

## Azioni correlate

<CardGroup cols={2}>

<Card title="Estrarre pagine" href="/docs/api/extract-pages-from-pdf">
  Conservare un sottoinsieme senza riordinare (l’ordine non conta).
</Card>

<Card title="Rimuovere pagine" href="/docs/api/remove-pages-from-pdf">
  Scartare pagine specifiche.
</Card>

<Card title="Invertire le pagine" href="/docs/api/reverse-pages-of-pdf">
  Invertire l’intero documento.
</Card>

<Card title="Unire documenti" href="/docs/api/merge-pdf-documents">
  Combinare prima più PDF.
</Card>

</CardGroup>
