Estrarre pagine da un PDF
Creare un nuovo PDF da una selezione di pagine di un PDF esistente.
Estrarre una o più pagine da un PDF in un nuovo documento. Selezionare le
pagine con il parametro pages. Se viene omesso,
vengono estratte tutte le pagine e il risultato le mantiene sempre nell’ordine
del documento. L’API è stateless: il documento viene elaborato nella sua
regione e non viene mai memorizzato.
Endpoint
/v1/extract_pagesDisponibile 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/extract_pages |
| Stati Uniti | https://us.api.pdfblocks.com/v1/extract_pages |
| HIPAA Stati Uniti | https://hipaa.api.pdfblocks.com/v1/extract_pages |
| Unione europea | https://eu.api.pdfblocks.com/v1/extract_pages |
| Regno Unito | https://uk.api.pdfblocks.com/v1/extract_pages |
| Canada | https://ca.api.pdfblocks.com/v1/extract_pages |
| Australia | https://au.api.pdfblocks.com/v1/extract_pages |
| Giappone | https://jp.api.pdfblocks.com/v1/extract_pages |
| India | https://in.api.pdfblocks.com/v1/extract_pages |
| Brasile | https://br.api.pdfblocks.com/v1/extract_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.
filefilerequiredIl documento PDF di input.
pagesstringLe pagine da estrarre, scritte come un intervallo di
pagine, ad esempio 1..3,5. Se viene omesso,
vengono estratte tutte le pagine. Massimo 1000 caratteri.
Selezionare le pagine
Il parametro pages accetta un elenco di numeri di pagina in base 1 e di
intervalli, separati da virgole. Viene trattato come un insieme: l’ordine e
i duplicati sono ignorati e le pagine estratte restano sempre nell’ordine del
documento. Per riorganizzare le pagine in un ordine arbitrario, usare invece
Riordinare le pagine.
| Schema | Seleziona |
|---|---|
| (omesso) | Tutte le pagine |
1 |
Solo la prima pagina |
1..3,5 |
Le pagine 1, 2, 3 e 5 |
2.. |
Dalla pagina 2 all’ultima pagina |
..-2 |
Dalla prima pagina alla penultima |
-1 |
L’ultima pagina |
Vedere Selezionare le pagine per il riferimento completo.
Esempi
Estrarre le pagine da 1 a 3 e la pagina 5 in un nuovo PDF:
curl https://api.pdfblocks.com/v1/extract_pages \
-H 'X-API-Key: your_api_key' \
-F file=@input.pdf \
-F pages='1..3,5' \
-o extracted.pdf# pip install requests
import requests
with open('input.pdf', 'rb') as file:
response = requests.post(
'https://api.pdfblocks.com/v1/extract_pages',
headers={'X-API-Key': 'your_api_key'},
files={'file': file},
data={'pages': '1..3,5'},
)
response.raise_for_status()
with open('extracted.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('pages', '1..3,5');
const response = await fetch('https://api.pdfblocks.com/v1/extract_pages', {
method: 'POST',
headers: { 'X-API-Key': 'your_api_key' },
body,
});
if (!response.ok) throw new Error(`Request failed: ${response.status}`);
await writeFile('extracted.pdf', Buffer.from(await response.arrayBuffer()));<?php
$ch = curl_init('https://api.pdfblocks.com/v1/extract_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'),
'pages' => '1..3,5',
],
]);
$pdf = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200) {
file_put_contents('extracted.pdf', $pdf);
}# gem install http
require 'http'
response = HTTP
.headers('X-API-Key' => 'your_api_key')
.post('https://api.pdfblocks.com/v1/extract_pages', form: {
file: HTTP::FormData::File.new('input.pdf'),
pages: '1..3,5',
})
File.write('extracted.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("pages", "1..3,5")
form.Close()
req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/extract_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("extracted.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..3,5"), "pages" },
};
var response = await client.PostAsync(
"https://api.pdfblocks.com/v1/extract_pages", form);
response.EnsureSuccessStatusCode();
await File.WriteAllBytesAsync(
"extracted.pdf", await response.Content.ReadAsByteArrayAsync());Risposta
In caso di successo, la risposta è 200 OK e il corpo contiene il PDF
estratto:
HTTP/1.1 200 OK
Content-Type: application/pdf
Content-Length: 22841L’output contiene solo le pagine selezionate, nell’ordine del documento. Scrivere il corpo direttamente in un file, come fanno gli esempi qui sopra; dalla nostra parte non viene memorizzato nulla.
Errori
Le richieste non riuscite restituiscono un corpo application/problem+json.
L’errore più frequente su questo endpoint è un 400, restituito quando pages
fa riferimento a una pagina che non esiste nel documento o quando file non è
un PDF leggibile. L’oggetto errors nomina ogni campo:
{
"type": "https://www.pdfblocks.com/docs/api/v1/error/400",
"title": "One or more validation errors occurred.",
"status": 400,
"errors": {
"pages": ["The pages field references a page that does not exist in the document."]
}
}Una X-API-Key assente 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.
Estrarre una sola pagina
curl https://api.pdfblocks.com/v1/extract_pages \
-H 'X-API-Key: your_api_key' \
-F file=@input.pdf \
-F pages='1' \
-o page-1.pdfimport requests
with open('input.pdf', 'rb') as file:
response = requests.post(
'https://api.pdfblocks.com/v1/extract_pages',
headers={'X-API-Key': 'your_api_key'},
files={'file': file},
data={'pages': '1'},
)
response.raise_for_status()
with open('page-1.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('pages', '1');
const response = await fetch('https://api.pdfblocks.com/v1/extract_pages', {
method: 'POST',
headers: { 'X-API-Key': 'your_api_key' },
body,
});
if (!response.ok) throw new Error(`Request failed: ${response.status}`);
await writeFile('page-1.pdf', Buffer.from(await response.arrayBuffer()));<?php
$ch = curl_init('https://api.pdfblocks.com/v1/extract_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'),
'pages' => '1',
],
]);
$pdf = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200) {
file_put_contents('page-1.pdf', $pdf);
}require 'http'
response = HTTP
.headers('X-API-Key' => 'your_api_key')
.post('https://api.pdfblocks.com/v1/extract_pages', form: {
file: HTTP::FormData::File.new('input.pdf'),
pages: '1',
})
File.write('page-1.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("pages", "1")
form.Close()
req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/extract_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("page-1.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"), "pages" },
};
var response = await client.PostAsync(
"https://api.pdfblocks.com/v1/extract_pages", form);
response.EnsureSuccessStatusCode();
await File.WriteAllBytesAsync(
"page-1.pdf", await response.Content.ReadAsByteArrayAsync());Estrarre le ultime tre pagine
curl https://api.pdfblocks.com/v1/extract_pages \
-H 'X-API-Key: your_api_key' \
-F file=@input.pdf \
-F pages='-3..-1' \
-o last-three.pdfimport requests
with open('input.pdf', 'rb') as file:
response = requests.post(
'https://api.pdfblocks.com/v1/extract_pages',
headers={'X-API-Key': 'your_api_key'},
files={'file': file},
data={'pages': '-3..-1'},
)
response.raise_for_status()
with open('last-three.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('pages', '-3..-1');
const response = await fetch('https://api.pdfblocks.com/v1/extract_pages', {
method: 'POST',
headers: { 'X-API-Key': 'your_api_key' },
body,
});
if (!response.ok) throw new Error(`Request failed: ${response.status}`);
await writeFile('last-three.pdf', Buffer.from(await response.arrayBuffer()));<?php
$ch = curl_init('https://api.pdfblocks.com/v1/extract_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'),
'pages' => '-3..-1',
],
]);
$pdf = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200) {
file_put_contents('last-three.pdf', $pdf);
}require 'http'
response = HTTP
.headers('X-API-Key' => 'your_api_key')
.post('https://api.pdfblocks.com/v1/extract_pages', form: {
file: HTTP::FormData::File.new('input.pdf'),
pages: '-3..-1',
})
File.write('last-three.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("pages", "-3..-1")
form.Close()
req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/extract_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-three.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"), "pages" },
};
var response = await client.PostAsync(
"https://api.pdfblocks.com/v1/extract_pages", form);
response.EnsureSuccessStatusCode();
await File.WriteAllBytesAsync(
"last-three.pdf", await response.Content.ReadAsByteArrayAsync());