Girar páginas de um PDF
Gire as páginas selecionadas de um PDF em um ângulo fixo, no sentido horário ou anti-horário.
Gire as páginas de um documento PDF em um ângulo fixo. Ângulos positivos giram
no sentido horário; ângulos negativos, no sentido anti-horário. Por padrão,
todas as páginas são giradas: use o parâmetro pages
para selecionar apenas um subconjunto. A API é stateless: seu documento é
processado na região e nunca é armazenado.
Endpoint
/v1/rotate_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/rotate_pages |
| Estados Unidos | https://us.api.pdfblocks.com/v1/rotate_pages |
| HIPAA Estados Unidos | https://hipaa.api.pdfblocks.com/v1/rotate_pages |
| União Europeia | 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 |
| Austrália | https://au.api.pdfblocks.com/v1/rotate_pages |
| Japão | https://jp.api.pdfblocks.com/v1/rotate_pages |
| Índia | https://in.api.pdfblocks.com/v1/rotate_pages |
| Brasil | https://br.api.pdfblocks.com/v1/rotate_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.
angleintegerrequiredA rotação a aplicar, em graus. Um dos ângulos válidos. Valores positivos giram no sentido horário; valores negativos, no sentido anti-horário.
pagesstringAs páginas a girar, escritas como um intervalo de
páginas, como 1..3,5. Quando omitido, todas as
páginas são giradas. Máximo de 1.000 caracteres.
Ângulos de rotação
Passe um dos valores a seguir para o parâmetro angle.
| Ângulo | Rotação |
|---|---|
0 |
Nenhuma rotação |
90 |
90° no sentido horário |
180 |
180° |
270 |
270° no sentido horário (90° no sentido anti-horário) |
-90 |
90° no sentido anti-horário |
-180 |
180° |
-270 |
270° no sentido anti-horário (90° no sentido horário) |
Ângulos positivos giram no sentido horário; ângulos negativos, no sentido anti-horário. Cada rotação se soma à rotação atual da página.
Selecionar páginas
O parâmetro pages aceita uma lista de números de página e intervalos
separados por vírgulas, começando em 1. Ele é tratado como um conjunto: a
ordem e as duplicatas são ignoradas, e as páginas são sempre giradas na ordem
do documento.
| Padrão | Seleciona |
|---|---|
| (omitir) | Todas as páginas |
1 |
Apenas a primeira página |
1..3,5 |
As páginas 1, 2, 3 e 5 |
2.. |
Da página 2 até a última |
..-2 |
Da primeira página até a penúltima |
-1 |
A última página |
Consulte Selecionar páginas para a referência completa.
Exemplos
Gire as três primeiras páginas 90° no sentido horário:
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# 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)// 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
$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);
}# 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?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)
}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());Resposta
Em caso de sucesso, a resposta é 200 OK com o PDF girado no corpo:
HTTP/1.1 200 OK
Content-Type: application/pdf
Content-Length: 48213A saída mantém as mesmas páginas e o mesmo conteúdo da entrada: só muda a rotação das páginas selecionadas. Grave 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 angle não é um dos
valores aceitos ou file não é um PDF legível. O objeto errors nomeia cada
campo:
{
"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."]
}
}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.
Endireite uma digitalização em paisagem
curl https://api.pdfblocks.com/v1/rotate_pages \
-H 'X-API-Key: your_api_key' \
-F file=@input.pdf \
-F angle=90 \
-o upright.pdfimport 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)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
$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);
}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?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)
}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());Vire todas as páginas em 180°
curl https://api.pdfblocks.com/v1/rotate_pages \
-H 'X-API-Key: your_api_key' \
-F file=@input.pdf \
-F angle=180 \
-o flipped.pdfimport 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)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
$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);
}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?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)
}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());