PDF Blocks
PreiseSupport
Kostenlos starten
Seite öffnen

Ein PDF nach Dateigröße aufteilen

Teilen Sie ein PDF in kleinere Dokumente auf, die jeweils eine maximale Größe in Bytes nicht überschreiten.

Teilen Sie ein PDF-Dokument in mehrere kleinere Dokumente auf, die jeweils eine maximale Dateigröße in Bytes nicht überschreiten. Diese Aktion gibt mehrere Dokumente zurück, verpackt in eine einzige Antwort gemäß dem Header Accept. Die API ist stateless: Ihr Dokument wird in der Region verarbeitet und niemals gespeichert.

Endpoint

POST
/v1/split_by_size

In allen Regionen verfügbar. Hinweise zu Routing und Datenresidenz finden Sie unter Regionen und Datenresidenz.

Region URL
Global https://api.pdfblocks.com/v1/split_by_size
USA https://us.api.pdfblocks.com/v1/split_by_size
HIPAA USA https://hipaa.api.pdfblocks.com/v1/split_by_size
Europäische Union https://eu.api.pdfblocks.com/v1/split_by_size
Vereinigtes Königreich https://uk.api.pdfblocks.com/v1/split_by_size
Kanada https://ca.api.pdfblocks.com/v1/split_by_size
Australien https://au.api.pdfblocks.com/v1/split_by_size
Japan https://jp.api.pdfblocks.com/v1/split_by_size
Indien https://in.api.pdfblocks.com/v1/split_by_size
Brasilien https://br.api.pdfblocks.com/v1/split_by_size

Authentifizierung

Authentifizieren Sie jede Anfrage mit Ihrem geheimen API-Schlüssel im Header X-API-Key, über HTTPS. Schlüssel erstellen und verwalten Sie im Dashboard. Einzelheiten finden Sie unter Authentifizierung.

Anfrage

Der Endpoint nimmt einen Anfragetext vom Typ multipart/form-data entgegen.

filefilerequired

Das PDF-Eingabedokument.

maximum_bytesintegerrequired

Die maximale Größe jedes Ausgabe-PDFs in Bytes. Muss 1 oder größer sein.

Beispiele

Teilen Sie ein Dokument so auf, dass jeder Teil höchstens 1 MB groß ist:

cURLbash
curl https://api.pdfblocks.com/v1/split_by_size \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F maximum_bytes=1048576 \
  -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_size',
        headers={'X-API-Key': 'your_api_key'},
        files={'file': file},
        data={'maximum_bytes': 1048576},  # 1 MB
    )

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('maximum_bytes', '1048576'); // 1 MB

const response = await fetch('https://api.pdfblocks.com/v1/split_by_size', {
  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_size');
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'),
        'maximum_bytes' => '1048576', // 1 MB
    ],
]);

$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_size', form: {
    file: HTTP::FormData::File.new('input.pdf'),
    maximum_bytes: '1048576', # 1 MB
  })

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("maximum_bytes", "1048576") // 1 MB
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/split_by_size", &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("1048576"), "maximum_bytes" }, // 1 MB
};

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

Antwort

Diese Aktion gibt mehrere Dokumente zurück, verpackt in eine einzige Antwort gemäß dem Anfrage-Header Accept. Siehe Antwortformate und Inhaltsaushandlung für die vollständige Referenz zur Aushandlung. Ohne den Header Accept ist ein ZIP-Archiv die Voreinstellung:

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

Wählen Sie die Verpackung über den Header Accept:

Header Accept Antwort
(nicht gesendet) application/zip (die Voreinstellung)
application/zip Ein ZIP-Archiv der Ausgabe-PDFs
application/json Ein JSON-Umschlag mit base64-kodierten Dokumenten
multipart/mixed Ein PDF pro Teil
alles andere 406 Not Acceptable

Die Ausgabedokumente heißen der Reihe nach 00001.pdf, 00002.pdf und so weiter.

Jeder Teil wird nach der gerenderten Ausgabegröße bis knapp unter maximum_bytes gefüllt, sodass die Teile sich der Grenze nähern, sie aber nie überschreiten. Die Ausnahme ist eine einzelne Seite, deren eigene Größe maximum_bytes bereits überschreitet: Sie wird als eigener Teil zurückgegeben, der die Grenze überschreitet, denn eine Seite wird niemals aufgeteilt.

Vollständigen Code, der eine Aktion zum Aufteilen aufruft und jedes Format entpackt (das ZIP extrahieren, den JSON-Umschlag dekodieren oder die Multipart-Teile lesen), finden Sie im Leitfaden Ein PDF aufteilen.

Fehler

Fehlgeschlagene Anfragen geben einen Text vom Typ application/problem+json zurück. Der häufigste Fehler an diesem Endpoint ist 400, der zurückgegeben wird, wenn maximum_bytes fehlt oder kleiner als 1 ist oder wenn file kein lesbares PDF ist. Das Objekt errors benennt jedes Feld:

{
  "type": "https://www.pdfblocks.com/docs/api/v1/error/400",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "errors": {
    "maximum_bytes": ["The field maximum_bytes must be greater than or equal to 1."]
  }
}

Wenn der Header Accept keinem der Typen application/zip, application/json oder multipart/mixed entspricht (zum Beispiel Accept: application/pdf), antwortet die API mit 406 Not Acceptable. Lassen Sie Accept weg, um die ZIP-Voreinstellung zu erhalten, oder fordern Sie einen der unterstützten Medientypen an. Ein fehlender oder ungültiger X-API-Key gibt einen 401 zurück. Alle Statuscodes und die vollständige Form der Antwort finden Sie unter Fehler.

Rezepte

Eine häufige Variante. Klappen Sie sie auf, um den Code in allen Sprachen zu sehen.

Die Teile als JSON-Umschlag empfangen

Senden Sie Accept: application/json, um alle Teile inline in einer einzigen Antwort zu erhalten, und dekodieren Sie dann den content jedes Eintrags aus Base64 in eine Datei, die nach seinem name benannt ist:

cURLbash
curl https://api.pdfblocks.com/v1/split_by_size \
  -H 'X-API-Key: your_api_key' \
  -H 'Accept: application/json' \
  -F file=@input.pdf \
  -F maximum_bytes=1048576 \
  | 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_size',
        headers={
            'X-API-Key': 'your_api_key',
            'Accept': 'application/json',
        },
        files={'file': file},
        data={'maximum_bytes': 1048576},
    )

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('maximum_bytes', '1048576');

const response = await fetch('https://api.pdfblocks.com/v1/split_by_size', {
  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_size');
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'),
        'maximum_bytes' => '1048576',
    ],
]);

$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_size', form: {
    file: HTTP::FormData::File.new('input.pdf'),
    maximum_bytes: '1048576',
  })

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("maximum_bytes", "1048576")
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/split_by_size", &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("1048576"), "maximum_bytes" },
};

var response = await client.PostAsync(
    "https://api.pdfblocks.com/v1/split_by_size", 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));
}

Verwandte Aktionen