Reordenar as páginas de um PDF
Reorganize as páginas de um PDF na ordem exata que você listar: uma repetição duplica uma página e uma omissão a descarta.
Reorganize as páginas de um PDF na ordem que você especificar com o parâmetro
page_order. Como page_order usa a
sintaxe de páginas ordenada, esta ação também
funciona como uma extração e reordenação combinadas: as páginas omitidas são
descartadas e uma página listada duas vezes é repetida. A API é stateless:
seu documento é processado na região e nunca é armazenado.
Endpoint
/v1/reorder_pagesDisponível em todas as regiões. Consulte Regiões e residência de dados para o roteamento e a residência de dados.
| Região | URL |
|---|---|
| Global | https://api.pdfblocks.com/v1/reorder_pages |
| Estados Unidos | https://us.api.pdfblocks.com/v1/reorder_pages |
| HIPAA Estados Unidos | https://hipaa.api.pdfblocks.com/v1/reorder_pages |
| União Europeia | 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 |
| Austrália | https://au.api.pdfblocks.com/v1/reorder_pages |
| Japão | https://jp.api.pdfblocks.com/v1/reorder_pages |
| Índia | https://in.api.pdfblocks.com/v1/reorder_pages |
| Brasil | https://br.api.pdfblocks.com/v1/reorder_pages |
Autenticação
Autentique cada requisição com sua chave de API secreta no cabeçalho
X-API-Key, por HTTPS. Crie e gerencie suas chaves no
dashboard. Consulte
Autenticação para mais detalhes.
Requisição
O endpoint aceita um corpo de requisição multipart/form-data.
filefilerequiredO documento PDF de entrada.
page_orderstringrequiredA ordem de páginas desejada, escrita na sintaxe de páginas
ordenada, como 3,1,2. As páginas omitidas são
descartadas e uma página listada mais de uma vez é repetida. Máximo de 1.000
caracteres.
Ordem das páginas
page_order é lido como uma lista ordenada, não como um conjunto: as
páginas saem exatamente como foram listadas. Uma página citada duas vezes é
emitida duas vezes, e qualquer página que você omitir é descartada. Um
intervalo pode até ir de trás para frente: 10..5 vai da página 10 até a
página 5.
Os números começam em 1, e um índice negativo conta a partir do fim, portanto
-1 é a última página.
page_order |
Produz |
|---|---|
3,1,2 |
As páginas 3, 1 e, em seguida, a 2 |
2.. |
Da página 2 até a última, em ordem |
-1,1..-2 |
A última página e, em seguida, todas as anteriores |
1,1,2.. |
A página 1 duas vezes e, depois, da página 2 adiante |
10..5 |
Da página 10 até a 5, em ordem inversa |
Consulte Selecionar páginas para a referência
completa, incluindo a diferença entre o page_order ordenado e o campo
pages, que é baseado em conjunto.
Exemplos
Coloque a página 3 em primeiro lugar e depois as páginas 1 e 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());Resposta
Em caso de sucesso, a resposta é 200 OK com o PDF reordenado no corpo:
HTTP/1.1 200 OK
Content-Type: application/pdf
Content-Length: 39184Grave o corpo diretamente em um arquivo, como fazem os exemplos acima; nada é armazenado do nosso lado.
Erros
Requisições com falha retornam um corpo application/problem+json. O erro
mais comum neste endpoint é um 400, retornado quando page_order está
malformado ou indica uma página que não existe no documento. O objeto errors
identifica o 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."]
}
}Uma X-API-Key ausente ou inválida retorna um 401. Consulte
Erros para todos os códigos de status e o formato completo
da resposta.
Receitas
Variações comuns. Expanda uma para vê-la em todas as linguagens.
Mova a última página para o início
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());Duplique a página de capa
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());