# PDF をページグループで分割する

PDF を、自分で定義したページグループに分割します。各グループが1つの出力ドキュメントになります。

PDF ドキュメントを、自分で定義したページグループに分割します。各グループが、記述した順に1つの出力 PDF になります。グループ内では、ページと範囲は [順序付きページ構文](/docs/api/selecting-pages) に従うため、記載したとおりの順序でそのまま出力されます。このアクションは複数のドキュメントを返し、`Accept` ヘッダーに応じて1つのレスポンスにまとめられます。この API はステートレスです。ドキュメントはリージョン内で処理され、保存されることはありません。

## エンドポイント

<Endpoint method="POST" path="/v1/split_by_groups" />

すべてのリージョンで利用できます。ルーティングとデータの保存地域については [リージョンとデータの保存地域](/docs/api/regions-and-data-residency) を参照してください。

| リージョン | URL |
| --- | --- |
| グローバル | `https://api.pdfblocks.com/v1/split_by_groups` |
| 日本 | `https://jp.api.pdfblocks.com/v1/split_by_groups` |
| 米国 | `https://us.api.pdfblocks.com/v1/split_by_groups` |
| HIPAA 米国 | `https://hipaa.api.pdfblocks.com/v1/split_by_groups` |
| 欧州連合 | `https://eu.api.pdfblocks.com/v1/split_by_groups` |
| 英国 | `https://uk.api.pdfblocks.com/v1/split_by_groups` |
| カナダ | `https://ca.api.pdfblocks.com/v1/split_by_groups` |
| オーストラリア | `https://au.api.pdfblocks.com/v1/split_by_groups` |
| インド | `https://in.api.pdfblocks.com/v1/split_by_groups` |
| ブラジル | `https://br.api.pdfblocks.com/v1/split_by_groups` |

## 認証

すべてのリクエストは、HTTPS 経由で `X-API-Key` ヘッダーにシークレット API キーを設定して認証してください。キーの作成と管理は [ダッシュボード](https://dashboard.pdfblocks.com) から行えます。詳細は [認証](/docs/api/authentication) を参照してください。

## リクエスト

このエンドポイントは `multipart/form-data` 形式のリクエストボディを受け付けます。

<ParamField name="file" type="file" required>
  入力する PDF ドキュメント。
</ParamField>

<ParamField name="groups" type="string" required>
  生成するページグループ。[ページグループの構文](#ページグループ) に従います。グループは `;` で区切り、グループ内ではページと範囲を `,` で区切って順序付きの規則に従います。各グループが、記述した順に1つの出力 PDF になります。例えば `2..8,29;1` は2つの PDF を生成します。ページ2〜8と29を含む PDF、そしてページ1のみの PDF です。
</ParamField>

### ページグループ

グループは `;` で区切ります。各グループ内では、ページと範囲は順序付き構文に従います。順序と重複が意味を持ち、同じページを2回指定すると2回出力され、範囲は逆順にもできます。各グループは、グループを記述した順に1つの出力 PDF になります。

例えば、`2..8,29;1` は2つのドキュメントを生成します。

| グループ | 出力 PDF | ページ |
| --- | --- | --- |
| `2..8,29` | `00001.pdf` | ページ2、3、4、5、6、7、8、続けて29 |
| `1` | `00002.pdf` | ページ1 |

グループ内では、`groups` は `page_order` と同じ順序付きの意味論を共有します。完全なリファレンスについては [ページを選択する](/docs/api/selecting-pages) を参照してください。

## サンプル

ドキュメントを2つの PDF に分割します。ページ2〜8と29の PDF、そしてページ1の PDF です。

<CodeGroup>

```bash title="cURL"
curl https://api.pdfblocks.com/v1/split_by_groups \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F groups='2..8,29;1' \
  -o parts.zip
```

```python title="Python"
# pip install requests
import requests

with open('input.pdf', 'rb') as file:
    response = requests.post(
        'https://api.pdfblocks.com/v1/split_by_groups',
        headers={'X-API-Key': 'your_api_key'},
        files={'file': file},
        data={'groups': '2..8,29;1'},
    )

response.raise_for_status()
with open('parts.zip', 'wb') as output:
    output.write(response.content)
```

```javascript title="Node.js"
// 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('groups', '2..8,29;1');

const response = await fetch('https://api.pdfblocks.com/v1/split_by_groups', {
  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()));
```

```php title="PHP"
<?php
$ch = curl_init('https://api.pdfblocks.com/v1/split_by_groups');
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'),
        'groups' => '2..8,29;1',
    ],
]);

$zip = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200) {
    file_put_contents('parts.zip', $zip);
}
```

```ruby title="Ruby"
# gem install http
require 'http'

response = HTTP
  .headers('X-API-Key' => 'your_api_key')
  .post('https://api.pdfblocks.com/v1/split_by_groups', form: {
    file: HTTP::FormData::File.new('input.pdf'),
    groups: '2..8,29;1',
  })

File.write('parts.zip', response.body) if response.status.success?
```

```go title="Go"
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("groups", "2..8,29;1")
	form.Close()

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

```csharp title="C#"
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("2..8,29;1"), "groups" },
};

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

</CodeGroup>

## レスポンス

このアクションは複数のドキュメントを返し、`Accept` リクエストヘッダーに応じて1つのレスポンスにまとめられます。ネゴシエーションの完全なリファレンスについては [レスポンスフォーマットとコンテンツネゴシエーション](/docs/api/response-formats) を参照してください。`Accept` ヘッダーがない場合、デフォルトは ZIP アーカイブです。

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

`Accept` ヘッダーで梱包形式を選択します。

| `Accept` ヘッダー | レスポンス |
| --- | --- |
| *(送信なし)* | `application/zip`（デフォルト） |
| `application/zip` | 出力 PDF の ZIP アーカイブ |
| `application/json` | base64 エンコードされたドキュメントの JSON エンベロープ |
| `multipart/mixed` | パートごとに1つの PDF |
| それ以外 | `406 Not Acceptable` |

API は、グループを記述した順に、グループごとに1つの出力ドキュメントを生成し、 `00001.pdf`、`00002.pdf` のように名付けます。

<Tip>
  分割アクションを呼び出し、各フォーマット（ZIP の展開、JSON エンベロープのデコード、multipart パートの読み取り）を扱うエンドツーエンドのコードは、[PDF を分割して出力を扱う](/docs/api/splitting-a-pdf) ガイドを参照してください。
</Tip>

## エラー

失敗したリクエストは `application/problem+json` 形式のボディを返します。このエンドポイントで最も多いのは `400` で、`groups` が指定されていないか形式が不正な場合、またはドキュメントに存在しないページを参照している場合に返されます。`errors` オブジェクトには各フィールド名が含まれます。

```json
{
  "type": "https://www.pdfblocks.com/docs/api/v1/error/400",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "errors": {
    "groups": ["The groups field references a page that does not exist in the document."]
  }
}
```

`Accept` ヘッダーが `application/zip`、`application/json`、`multipart/mixed` のいずれにも一致しない場合（例えば `Accept: application/pdf`）、API は `406 Not Acceptable` を返します。`Accept` を省略してデフォルトの ZIP を使うか、サポートされているメディアタイプのいずれかをリクエストしてください。`X-API-Key` が未指定または無効な場合は `401` が返されます。すべてのステータスコードとレスポンスの完全な形式については [エラー](/docs/api/errors) を参照してください。

## 応用例

よくあるバリエーションです。展開するとすべての言語のコードが表示されます。

<AccordionGroup>

<Accordion title="パートを JSON エンベロープとして受け取る">

`Accept: application/json` を送ると、すべてのパートが1つのレスポンスにインラインで含まれます。各エントリの `content` を base64 デコードし、`name` にちなんだファイル名で保存します。

<CodeGroup>

```bash title="cURL"
curl https://api.pdfblocks.com/v1/split_by_groups \
  -H 'X-API-Key: your_api_key' \
  -H 'Accept: application/json' \
  -F file=@input.pdf \
  -F groups='2..8,29;1' \
  | jq -r '.documents[] | .name + " " + .content' \
  | while read -r name content; do
      echo "$content" | base64 --decode > "$name"
    done
```

```python title="Python"
# pip install requests
import base64
import requests

with open('input.pdf', 'rb') as file:
    response = requests.post(
        'https://api.pdfblocks.com/v1/split_by_groups',
        headers={
            'X-API-Key': 'your_api_key',
            'Accept': 'application/json',
        },
        files={'file': file},
        data={'groups': '2..8,29;1'},
    )

response.raise_for_status()
for document in response.json()['documents']:
    with open(document['name'], 'wb') as output:
        output.write(base64.b64decode(document['content']))
```

```javascript title="Node.js"
// 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('groups', '2..8,29;1');

const response = await fetch('https://api.pdfblocks.com/v1/split_by_groups', {
  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'));
}
```

```php title="PHP"
<?php
$ch = curl_init('https://api.pdfblocks.com/v1/split_by_groups');
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'),
        'groups' => '2..8,29;1',
    ],
]);

$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']));
    }
}
```

```ruby title="Ruby"
# 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_groups', form: {
    file: HTTP::FormData::File.new('input.pdf'),
    groups: '2..8,29;1',
  })

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

```go title="Go"
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("groups", "2..8,29;1")
	form.Close()

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

```csharp title="C#"
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("2..8,29;1"), "groups" },
};

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

</CodeGroup>

</Accordion>

</AccordionGroup>

## 関連アクション

<CardGroup cols={2}>

<Card title="ページ数で分割する" href="/docs/api/split-pdf-by-page-count">
  固定サイズのチャンクに分割します。
</Card>

<Card title="指定したページで分割する" href="/docs/api/split-pdf-at-page">
  境界で2つのドキュメントに分割します。
</Card>

<Card title="ページの並べ替え" href="/docs/api/reorder-pages-of-pdf">
  単一の出力内でページを並べ替えます。
</Card>

<Card title="ページを抽出する" href="/docs/api/extract-pages-from-pdf">
  1つのページ範囲を残します。
</Card>

</CardGroup>
