# PDF のページを並べ替える

PDF のページを指定したとおりの順序に並べ替えます。同じページを繰り返し指定すると複製され、指定しなかったページは除外されます。

PDF のページを、[`page_order`](#ページの順序) パラメーターで指定した任意の順序に並べ替えます。`page_order` は[順序付きのページ構文](/docs/api/selecting-pages)を使用するため、このアクションは抽出と並べ替えを組み合わせた処理としても機能します。指定しなかったページは除外され、2回指定したページは繰り返されます。この API はステートレスです。ドキュメントはリージョン内で処理され、保存されることはありません。

## エンドポイント

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

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

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

## 認証

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

## リクエスト

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

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

<ParamField name="page_order" type="string" required>
  希望するページの順序を、[順序付きのページ構文](#ページの順序)で `3,1,2` のように指定します。指定しなかったページは除外され、複数回指定したページは繰り返されます。最大1000文字です。
</ParamField>

### ページの順序

`page_order` は**集合**ではなく**順序付きリスト**として読み取られます。ページは指定したとおりの順序でそのまま出力されます。2回指定したページは2回出力され、指定しなかったページは除外されます。範囲は逆方向に指定することもでき、`10..5` はページ10からページ5まで下る形になります。

番号は1から始まり、負のインデックスは末尾から数えます。したがって `-1` は最後のページを指します。

| `page_order` | 結果                                             |
| ------------ | -------------------------------------------------- |
| `3,1,2`      | ページ3、1、2の順                                 |
| `2..`        | ページ2から最後まで、順番どおり                   |
| `-1,1..-2`   | 最後のページ、続いてそれより前のすべてのページ    |
| `1,1,2..`    | ページ1を2回、続いてページ2以降                   |
| `10..5`      | ページ10からページ5まで、逆順                     |

順序付きの `page_order` と集合ベースの `pages` フィールドの違いを含め、完全なリファレンスについては[ページの選択](/docs/api/selecting-pages)を参照してください。

## 例

ページ3を先頭にし、続けてページ1と2を配置します。

<CodeGroup>

```bash title="cURL"
curl https://api.pdfblocks.com/v1/reorder_pages \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F page_order='3,1,2' \
  -o reordered.pdf
```

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

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

response.raise_for_status()
with open('reordered.pdf', '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('page_order', '3,1,2');

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

if (!response.ok) throw new Error(`Request failed: ${response.status}`);
await writeFile('reordered.pdf', Buffer.from(await response.arrayBuffer()));
```

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

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

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

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

File.write('reordered.pdf', 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("page_order", "3,1,2")
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/reorder_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("reordered.pdf")
	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("3,1,2"), "page_order" },
};

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

</CodeGroup>

## レスポンス

成功すると、レスポンスは `200 OK` となり、ボディに並べ替えられた PDF が入ります。

```http
HTTP/1.1 200 OK
Content-Type: application/pdf
Content-Length: 39184
```

上記の例のように、ボディを直接ファイルへストリーミングしてください。当社側には何も保存されません。

## エラー

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

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

`X-API-Key` が存在しないか無効な場合は `401` が返されます。ステータスコードとレスポンスの完全な形式については、[エラー](/docs/api/errors)を参照してください。

## バリエーション

よく使われるバリエーションです。展開すると、各言語での実装を確認できます。

<AccordionGroup>

<Accordion title="最後のページを先頭に移動">

<CodeGroup>

```bash title="cURL"
curl https://api.pdfblocks.com/v1/reorder_pages \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F page_order='-1,1..-2' \
  -o last-first.pdf
```

```python title="Python"
import requests

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

response.raise_for_status()
with open('last-first.pdf', 'wb') as output:
    output.write(response.content)
```

```javascript title="Node.js"
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_order', '-1,1..-2');

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

if (!response.ok) throw new Error(`Request failed: ${response.status}`);
await writeFile('last-first.pdf', Buffer.from(await response.arrayBuffer()));
```

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

$pdf = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200) {
    file_put_contents('last-first.pdf', $pdf);
}
```

```ruby title="Ruby"
require 'http'

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

File.write('last-first.pdf', 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("page_order", "-1,1..-2")
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/reorder_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-first.pdf")
	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("-1,1..-2"), "page_order" },
};

var response = await client.PostAsync(
    "https://api.pdfblocks.com/v1/reorder_pages", form);
response.EnsureSuccessStatusCode();
await File.WriteAllBytesAsync(
    "last-first.pdf", await response.Content.ReadAsByteArrayAsync());
```

</CodeGroup>

</Accordion>

<Accordion title="表紙ページを複製">

<CodeGroup>

```bash title="cURL"
curl https://api.pdfblocks.com/v1/reorder_pages \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F page_order='1,1..-1' \
  -o doubled-cover.pdf
```

```python title="Python"
import requests

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

response.raise_for_status()
with open('doubled-cover.pdf', 'wb') as output:
    output.write(response.content)
```

```javascript title="Node.js"
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_order', '1,1..-1');

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

if (!response.ok) throw new Error(`Request failed: ${response.status}`);
await writeFile('doubled-cover.pdf', Buffer.from(await response.arrayBuffer()));
```

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

$pdf = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200) {
    file_put_contents('doubled-cover.pdf', $pdf);
}
```

```ruby title="Ruby"
require 'http'

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

File.write('doubled-cover.pdf', 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("page_order", "1,1..-1")
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/reorder_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("doubled-cover.pdf")
	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("1,1..-1"), "page_order" },
};

var response = await client.PostAsync(
    "https://api.pdfblocks.com/v1/reorder_pages", form);
response.EnsureSuccessStatusCode();
await File.WriteAllBytesAsync(
    "doubled-cover.pdf", await response.Content.ReadAsByteArrayAsync());
```

</CodeGroup>

</Accordion>

</AccordionGroup>

## 関連アクション

<CardGroup cols={2}>

<Card title="ページを抽出する" href="/docs/api/extract-pages-from-pdf">
  並べ替えずに一部のページだけを保持します（順序を問いません）。
</Card>

<Card title="ページを削除" href="/docs/api/remove-pages-from-pdf">
  特定のページを除外します。
</Card>

<Card title="ページを反転" href="/docs/api/reverse-pages-of-pdf">
  ドキュメント全体を反転します。
</Card>

<Card title="ドキュメントを結合" href="/docs/api/merge-pdf-documents">
  まず複数の PDF を結合します。
</Card>

</CardGroup>
