Reordenar las páginas de un PDF
Reorganice las páginas de un PDF en el orden exacto que indique: una repetición duplica una página y una omisión la descarta.
Reorganice las páginas de un PDF en el orden que indique con el parámetro
page_order. Como page_order usa la sintaxis de páginas
ordenada, esta acción sirve además como extraer y
reordenar a la vez: las páginas omitidas se descartan y una página listada
dos veces se repite. La API es stateless: su documento se procesa en la
región y nunca se almacena.
Endpoint
/v1/reorder_pagesDisponible en todas las regiones. Consulte Regiones y residencia de datos para el enrutamiento y la residencia de datos.
| Región | URL |
|---|---|
| Global | https://api.pdfblocks.com/v1/reorder_pages |
| Estados Unidos | https://us.api.pdfblocks.com/v1/reorder_pages |
| HIPAA de EE. UU. | https://hipaa.api.pdfblocks.com/v1/reorder_pages |
| Unión Europea | https://eu.api.pdfblocks.com/v1/reorder_pages |
| Reino Unido | https://uk.api.pdfblocks.com/v1/reorder_pages |
| Canadá | https://ca.api.pdfblocks.com/v1/reorder_pages |
| Australia | https://au.api.pdfblocks.com/v1/reorder_pages |
| Japón | https://jp.api.pdfblocks.com/v1/reorder_pages |
| India | https://in.api.pdfblocks.com/v1/reorder_pages |
| Brasil | https://br.api.pdfblocks.com/v1/reorder_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. Consulte
Autenticación para más detalles.
Solicitud
El endpoint acepta un cuerpo de solicitud multipart/form-data.
filefilerequiredEl documento PDF de entrada.
page_orderstringrequiredEl orden de páginas deseado, escrito con la sintaxis de páginas
ordenada tipo 3,1,2. Las páginas omitidas se descartan y
una página listada más de una vez se repite. Máximo 1000 caracteres.
Orden de las páginas
page_order se lee como una lista ordenada, no como un conjunto: las
páginas salen exactamente como se listan. Una página nombrada dos veces se
emite dos veces, y cualquier página que omita se descarta. Un rango puede
incluso ir hacia atrás: 10..5 recorre de la página 10 a la página 5.
Los números están en base 1, y un índice negativo cuenta desde el final, así
que -1 es la última página.
page_order |
Produce |
|---|---|
3,1,2 |
Las páginas 3, 1 y luego la 2 |
2.. |
De la página 2 a la última, en orden |
-1,1..-2 |
La última página y después todas las anteriores |
1,1,2.. |
La página 1 dos veces y después de la 2 en adelante |
10..5 |
De la página 10 a la 5, en orden inverso |
Consulte Seleccionar páginas para ver la
referencia completa, incluida la diferencia entre el page_order ordenado y
el campo pages basado en conjuntos.
Ejemplos
Ponga primero la página 3 y después las páginas 1 y 2:
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# 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.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
$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);
}# 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?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)
}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());Respuesta
Si todo va bien, la respuesta es 200 OK con el PDF reordenado como cuerpo:
HTTP/1.1 200 OK
Content-Type: application/pdf
Content-Length: 39184Escriba 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
page_order está mal formado o nombra una página que el documento no tiene:
el objeto errors identifica el 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 ausente o no válida devuelve un 401. Consulte
Errores 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.
Mover la última página al principio
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.pdfimport 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)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
$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);
}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?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)
}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());Duplicar la portada
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.pdfimport 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)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
$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);
}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?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)
}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());