拆分 PDF
将 PDF 按页拆分为多个文件。
请求
POST
https://api.bitaloka.io/v1/pdf/split Multipart 表单→
application/zip 参数
| 名称 | 类型 | 描述 |
|---|---|---|
file必填 | PDF 文件 | The PDF to process (multipart file field).示例: document.pdf |
代码示例
由同一来源生成,并已针对线上 API 测试。
curl -sS -X POST "https://api.bitaloka.io/v1/pdf/split" \
-H "X-API-Key: $BITALOKA_API_KEY" \
-F "file=@document.pdf;type=application/pdf" \
--fail-with-body -o split.zip import { openAsBlob } from 'node:fs'
import { writeFile } from 'node:fs/promises'
const apiKey = process.env.BITALOKA_API_KEY ?? ''
const form = new FormData()
form.append('file', await openAsBlob('document.pdf', { type: 'application/pdf' }), 'document.pdf')
const res = await fetch("https://api.bitaloka.io/v1/pdf/split", {
method: 'POST',
headers: { 'X-API-Key': apiKey },
body: form,
})
if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`)
await writeFile('split.zip', new Uint8Array(await res.arrayBuffer()))
console.log('Saved split.zip') import { openAsBlob } from 'node:fs'
import { writeFile } from 'node:fs/promises'
const apiKey = process.env.BITALOKA_API_KEY ?? ''
const form = new FormData()
form.append('file', await openAsBlob('document.pdf', { type: 'application/pdf' }), 'document.pdf')
const res = await fetch("https://api.bitaloka.io/v1/pdf/split", {
method: 'POST',
headers: { 'X-API-Key': apiKey },
body: form,
})
if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`)
await writeFile('split.zip', new Uint8Array(await res.arrayBuffer()))
console.log('Saved split.zip') import os
from pathlib import Path
import requests
API_KEY = os.environ.get("BITALOKA_API_KEY", "")
res = requests.post(
"https://api.bitaloka.io/v1/pdf/split",
headers={"X-API-Key": API_KEY},
files=[
("file", ("document.pdf", Path("document.pdf").read_bytes(), "application/pdf")),
],
timeout=120,
)
res.raise_for_status()
Path("split.zip").write_bytes(res.content)
print("Saved split.zip") import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class Example {
public static void main(String[] args) throws Exception {
var client = HttpClient.newHttpClient();
var apiKey = System.getenv().getOrDefault("BITALOKA_API_KEY", "");
var boundary = "bitaloka-" + UUID.randomUUID();
var body = new ArrayList<byte[]>();
addFile(body, boundary, "file", Path.of("document.pdf"), "application/pdf");
body.add(("--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8));
var request = HttpRequest.newBuilder(URI.create("https://api.bitaloka.io/v1/pdf/split"))
.header("X-API-Key", apiKey)
.header("Content-Type", "multipart/form-data; boundary=" + boundary)
.POST(HttpRequest.BodyPublishers.ofByteArrays(body))
.build();
var response = client.send(request, HttpResponse.BodyHandlers.ofByteArray());
if (response.statusCode() >= 400) {
throw new RuntimeException("HTTP " + response.statusCode() + ": " + new String(response.body()));
}
Files.write(Path.of("split.zip"), response.body());
System.out.println("Saved split.zip");
}
static void addFile(List<byte[]> body, String boundary, String name, Path file, String type) throws IOException {
body.add(("--" + boundary + "\r\nContent-Disposition: form-data; name=\"" + name + "\"; filename=\"" + file.getFileName() + "\"\r\nContent-Type: " + type + "\r\n\r\n").getBytes(StandardCharsets.UTF_8));
body.add(Files.readAllBytes(file));
body.add("\r\n".getBytes(StandardCharsets.UTF_8));
}
} using var http = new HttpClient();
http.DefaultRequestHeaders.Add("X-API-Key", Environment.GetEnvironmentVariable("BITALOKA_API_KEY") ?? "");
using var form = new MultipartFormDataContent();
var file1 = new ByteArrayContent(await File.ReadAllBytesAsync("document.pdf"));
file1.Headers.ContentType = new("application/pdf");
form.Add(file1, "file", "document.pdf");
var res = await http.PostAsync("https://api.bitaloka.io/v1/pdf/split", form);
if (!res.IsSuccessStatusCode)
throw new HttpRequestException($"HTTP {(int)res.StatusCode}: {await res.Content.ReadAsStringAsync()}");
await File.WriteAllBytesAsync("split.zip", await res.Content.ReadAsByteArrayAsync());
Console.WriteLine("Saved split.zip"); <?php
$ch = curl_init('https://api.bitaloka.io/v1/pdf/split');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['X-API-Key: ' . getenv('BITALOKA_API_KEY')],
CURLOPT_POSTFIELDS => [
'file' => new CURLFile('document.pdf', 'application/pdf'),
],
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
if ($body === false || $status >= 400) {
throw new RuntimeException("HTTP $status: $body");
}
file_put_contents('split.zip', $body);
echo "Saved split.zip\n"; package main
import (
"bytes"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/textproto"
"os"
"path/filepath"
)
func main() {
var buf bytes.Buffer
w := multipart.NewWriter(&buf)
check(addFile(w, "file", "document.pdf", "application/pdf"))
check(w.Close())
req, err := http.NewRequest("POST", "https://api.bitaloka.io/v1/pdf/split", &buf)
check(err)
req.Header.Set("X-API-Key", os.Getenv("BITALOKA_API_KEY"))
req.Header.Set("Content-Type", w.FormDataContentType())
res, err := http.DefaultClient.Do(req)
check(err)
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
check(err)
if res.StatusCode >= 400 {
panic(fmt.Sprintf("HTTP %d: %s", res.StatusCode, body))
}
check(os.WriteFile("split.zip", body, 0o644))
fmt.Println("Saved split.zip")
}
func addFile(w *multipart.Writer, field, path, contentType string) error {
data, err := os.ReadFile(path)
if err != nil {
return err
}
h := make(textproto.MIMEHeader)
h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="%s"; filename="%s"`, field, filepath.Base(path)))
h.Set("Content-Type", contentType)
part, err := w.CreatePart(h)
if err != nil {
return err
}
_, err = part.Write(data)
return err
}
func check(err error) {
if err != nil {
panic(err)
}
} // build.gradle.kts: implementation("com.squareup.okhttp3:okhttp:4.12.0")
import java.io.File
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.asRequestBody
fun main() {
val client = OkHttpClient()
val body = MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", "document.pdf", File("document.pdf").asRequestBody("application/pdf".toMediaType()))
.build()
val request = Request.Builder()
.url("https://api.bitaloka.io/v1/pdf/split")
.header("X-API-Key", System.getenv("BITALOKA_API_KEY") ?: "")
.post(body)
.build()
client.newCall(request).execute().use { res ->
check(res.isSuccessful) { "HTTP ${res.code}: ${res.body?.string()}" }
File("split.zip").writeBytes(res.body!!.bytes())
println("Saved split.zip")
}
} import Foundation
var request = URLRequest(url: URL(string: "https://api.bitaloka.io/v1/pdf/split")!)
request.setValue(ProcessInfo.processInfo.environment["BITALOKA_API_KEY"] ?? "", forHTTPHeaderField: "X-API-Key")
request.httpMethod = "POST"
let boundary = "bitaloka-\(UUID().uuidString)"
var body = Data()
func addFile(_ name: String, _ path: String, _ type: String) throws {
let url = URL(fileURLWithPath: path)
body.append("--\(boundary)\r\nContent-Disposition: form-data; name=\"\(name)\"; filename=\"\(url.lastPathComponent)\"\r\nContent-Type: \(type)\r\n\r\n".data(using: .utf8)!)
body.append(try Data(contentsOf: url))
body.append("\r\n".data(using: .utf8)!)
}
try addFile("file", "document.pdf", "application/pdf")
body.append("--\(boundary)--\r\n".data(using: .utf8)!)
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let (data, response) = try await URLSession.shared.upload(for: request, from: body)
guard let http = response as? HTTPURLResponse, http.statusCode < 400 else {
fatalError("Request failed: \(String(decoding: data, as: UTF8.self))")
}
try data.write(to: URL(fileURLWithPath: "split.zip"))
print("Saved split.zip") // Cargo.toml: reqwest = { version = "0.12", features = ["blocking", "multipart"] }
fn main() -> Result<(), Box<dyn std::error::Error>> {
let api_key = std::env::var("BITALOKA_API_KEY").unwrap_or_default();
let client = reqwest::blocking::Client::new();
let form = reqwest::blocking::multipart::Form::new()
.file("file", "document.pdf")?;
let res = client
.post("https://api.bitaloka.io/v1/pdf/split")
.header("X-API-Key", api_key)
.multipart(form)
.send()?
.error_for_status()?;
std::fs::write("split.zip", res.bytes()?)?;
println!("Saved split.zip");
Ok(())
} 响应
以
application/zip 格式返回处理后的文件。示例代码将其保存为 split.zip。在 AI 智能体中使用
在 Bitaloka MCP 服务器上,此服务对应 pdf_split 工具。 MCP 服务器 →