PDF Blocks
PrezziSupporto
Iniziare gratis
Aprire la pagina

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. Poiché page_order usa la sintassi ordinata delle pagine, 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

POST
/v1/reorder_pages

Disponibile in tutte le regioni. Vedere Regioni e residenza dei dati 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. Vedere Autenticazione per i dettagli.

Richiesta

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

filefilerequired

Il documento PDF di input.

page_orderstringrequired

L’ordine delle pagine desiderato, scritto con la sintassi ordinata 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.

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 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:

cURLbash
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
Pythonpython
# 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)
Node.jsjavascript
// 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()));
PHPphp
<?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);
}
Rubyruby
# 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?
Gogo
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)
}
C#csharp
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());

Risposta

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

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:

{
  "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 per tutti i codici di stato e la forma completa della risposta.

Ricette

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

Spostare l’ultima pagina all’inizio
cURLbash
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
Pythonpython
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)
Node.jsjavascript
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()));
PHPphp
<?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);
}
Rubyruby
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?
Gogo
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)
}
C#csharp
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());
Duplicare la pagina di copertina
cURLbash
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
Pythonpython
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)
Node.jsjavascript
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()));
PHPphp
<?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);
}
Rubyruby
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?
Gogo
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)
}
C#csharp
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());

Azioni correlate