PDF Blocks
PrezziSupporto
Iniziare gratis
Aprire la pagina

Dividere un PDF per numero di pagine

Dividere un PDF in parti consecutive con un numero fisso di pagine, lasciando quel che avanza nell’ultima parte.

Dividere un documento PDF in parti consecutive di un numero fisso di pagine: l’ultima parte contiene le pagine rimanenti e può essere più piccola. Questa azione restituisce più documenti, impacchettati in un’unica risposta in base all’intestazione Accept. L’API è stateless: il documento viene elaborato nella sua regione e non viene mai memorizzato.

Endpoint

POST
/v1/split_by_page_count

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/split_by_page_count
Stati Uniti https://us.api.pdfblocks.com/v1/split_by_page_count
HIPAA Stati Uniti https://hipaa.api.pdfblocks.com/v1/split_by_page_count
Unione europea https://eu.api.pdfblocks.com/v1/split_by_page_count
Regno Unito https://uk.api.pdfblocks.com/v1/split_by_page_count
Canada https://ca.api.pdfblocks.com/v1/split_by_page_count
Australia https://au.api.pdfblocks.com/v1/split_by_page_count
Giappone https://jp.api.pdfblocks.com/v1/split_by_page_count
India https://in.api.pdfblocks.com/v1/split_by_page_count
Brasile https://br.api.pdfblocks.com/v1/split_by_page_count

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_countintegerrequired

Il numero di pagine di ogni PDF di output. Deve essere 1 o superiore. L’ultima parte contiene le pagine rimanenti e può essere più piccola.

Esempi

Dividere un documento in parti da 10 pagine e salvare l’archivio ZIP:

cURLbash
curl https://api.pdfblocks.com/v1/split_by_page_count \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F page_count=10 \
  -o parts.zip
Pythonpython
# pip install requests
import requests

with open('input.pdf', 'rb') as file:
    response = requests.post(
        'https://api.pdfblocks.com/v1/split_by_page_count',
        headers={'X-API-Key': 'your_api_key'},
        files={'file': file},
        data={'page_count': 10},
    )

response.raise_for_status()
with open('parts.zip', '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_count', '10');

const response = await fetch('https://api.pdfblocks.com/v1/split_by_page_count', {
  method: 'POST',
  headers: { 'X-API-Key': 'your_api_key' },
  body,
});

if (!response.ok) throw new Error(`Request failed: ${response.status}`);
await writeFile('parts.zip', Buffer.from(await response.arrayBuffer()));
PHPphp
<?php
$ch = curl_init('https://api.pdfblocks.com/v1/split_by_page_count');
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_count' => '10',
    ],
]);

$zip = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200) {
    file_put_contents('parts.zip', $zip);
}
Rubyruby
# gem install http
require 'http'

response = HTTP
  .headers('X-API-Key' => 'your_api_key')
  .post('https://api.pdfblocks.com/v1/split_by_page_count', form: {
    file: HTTP::FormData::File.new('input.pdf'),
    page_count: '10',
  })

File.write('parts.zip', 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_count", "10")
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/split_by_page_count", &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("parts.zip")
	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("10"), "page_count" },
};

var response = await client.PostAsync(
    "https://api.pdfblocks.com/v1/split_by_page_count", form);
response.EnsureSuccessStatusCode();
await File.WriteAllBytesAsync(
    "parts.zip", await response.Content.ReadAsByteArrayAsync());

Risposta

Questa azione restituisce più documenti, impacchettati in un’unica risposta secondo l’intestazione di richiesta Accept. Vedere Formati di risposta e negoziazione del contenuto per il riferimento completo sulla negoziazione. Senza intestazione Accept, il valore predefinito è un archivio ZIP:

HTTP/1.1 200 OK
Content-Type: application/zip

Selezionare l’impacchettamento con l’intestazione Accept:

Intestazione Accept Risposta
(nessuna inviata) application/zip: il valore predefinito
application/zip Un archivio ZIP dei PDF di output
application/json Una busta JSON di documenti codificati in base64
multipart/mixed Un PDF per ogni parte
qualsiasi altro valore 406 Not Acceptable

I documenti di output sono denominati 00001.pdf, 00002.pdf e così via, in ordine.

Per codice end-to-end che chiama un’azione di divisione e spacchetta ogni formato (estraendo lo ZIP, decodificando la busta JSON o leggendo le parti multipart), vedere la guida Dividere un PDF.

Errori

Le richieste non riuscite restituiscono un corpo application/problem+json. L’errore più frequente su questo endpoint è un 400, restituito quando page_count è assente o inferiore a 1, oppure 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": {
    "page_count": ["The field page_count must be greater than or equal to 1."]
  }
}

Se l’intestazione Accept non corrisponde a nessuno tra application/zip, application/json e multipart/mixed, ad esempio Accept: application/pdf, l’API risponde con 406 Not Acceptable. Omettere Accept per prendere lo ZIP predefinito, oppure richiedere uno dei tipi di media supportati. 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

Una variante comune. Espanderla per vedere il codice in tutti i linguaggi.

Ricevere le parti come busta JSON

Inviare Accept: application/json per ottenere tutte le parti in linea in un’unica risposta, quindi decodificare da base64 il content di ogni voce in un file con il nome indicato dal suo name:

cURLbash
curl https://api.pdfblocks.com/v1/split_by_page_count \
  -H 'X-API-Key: your_api_key' \
  -H 'Accept: application/json' \
  -F file=@input.pdf \
  -F page_count=10 \
  | jq -r '.documents[] | .name + " " + .content' \
  | while read -r name content; do
      echo "$content" | base64 --decode > "$name"
    done
Pythonpython
# pip install requests
import base64
import requests

with open('input.pdf', 'rb') as file:
    response = requests.post(
        'https://api.pdfblocks.com/v1/split_by_page_count',
        headers={
            'X-API-Key': 'your_api_key',
            'Accept': 'application/json',
        },
        files={'file': file},
        data={'page_count': 10},
    )

response.raise_for_status()
for document in response.json()['documents']:
    with open(document['name'], 'wb') as output:
        output.write(base64.b64decode(document['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_count', '10');

const response = await fetch('https://api.pdfblocks.com/v1/split_by_page_count', {
  method: 'POST',
  headers: { 'X-API-Key': 'your_api_key', Accept: 'application/json' },
  body,
});

if (!response.ok) throw new Error(`Request failed: ${response.status}`);
const { documents } = await response.json();
for (const doc of documents) {
  await writeFile(doc.name, Buffer.from(doc.content, 'base64'));
}
PHPphp
<?php
$ch = curl_init('https://api.pdfblocks.com/v1/split_by_page_count');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'X-API-Key: your_api_key',
        'Accept: application/json',
    ],
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => [
        'file' => new CURLFile('input.pdf', 'application/pdf'),
        'page_count' => '10',
    ],
]);

$body = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200) {
    foreach (json_decode($body, true)['documents'] as $document) {
        file_put_contents($document['name'], base64_decode($document['content']));
    }
}
Rubyruby
# gem install http
require 'base64'
require 'http'
require 'json'

response = HTTP
  .headers('X-API-Key' => 'your_api_key', 'Accept' => 'application/json')
  .post('https://api.pdfblocks.com/v1/split_by_page_count', form: {
    file: HTTP::FormData::File.new('input.pdf'),
    page_count: '10',
  })

if response.status.success?
  JSON.parse(response.body)['documents'].each do |document|
    File.write(document['name'], Base64.decode64(document['content']))
  end
end
Gogo
package main

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"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_count", "10")
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/split_by_page_count", &buf)
	req.Header.Set("Content-Type", form.FormDataContentType())
	req.Header.Set("X-API-Key", "your_api_key")
	req.Header.Set("Accept", "application/json")

	res, _ := http.DefaultClient.Do(req)
	defer res.Body.Close()

	var result struct {
		Documents []struct {
			Name    string `json:"name"`
			Content string `json:"content"`
		} `json:"documents"`
	}
	json.NewDecoder(res.Body).Decode(&result)

	for _, doc := range result.Documents {
		data, _ := base64.StdEncoding.DecodeString(doc.Content)
		os.WriteFile(doc.Name, data, 0644)
	}
}
C#csharp
using System.Text.Json;

using var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-API-Key", "your_api_key");
client.DefaultRequestHeaders.Add("Accept", "application/json");

using var form = new MultipartFormDataContent
{
    { new ByteArrayContent(File.ReadAllBytes("input.pdf")), "file", "input.pdf" },
    { new StringContent("10"), "page_count" },
};

var response = await client.PostAsync(
    "https://api.pdfblocks.com/v1/split_by_page_count", form);
response.EnsureSuccessStatusCode();

using var json = JsonDocument.Parse(
    await response.Content.ReadAsStringAsync());
foreach (var document in json.RootElement.GetProperty("documents").EnumerateArray())
{
    var name = document.GetProperty("name").GetString()!;
    var content = document.GetProperty("content").GetString()!;
    await File.WriteAllBytesAsync(name, Convert.FromBase64String(content));
}

Azioni correlate