# PDF からページを削除する

PDF から一部のページを削除します。少なくとも1ページは必ず残ります。

PDF ドキュメントから1ページ以上を削除します。除外するページは [`pages`](#ページの選択) パラメーターで選択します。少なくとも1ページは残す必要があるため、選択ですべてのページを対象にすることはできません。この API はステートレスです。ドキュメントはリージョン内で処理され、保存されることはありません。

## エンドポイント

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

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

| リージョン | URL                                                |
| ---------- | --------------------------------------------------- |
| グローバル | `https://api.pdfblocks.com/v1/remove_pages`         |
| 日本       | `https://jp.api.pdfblocks.com/v1/remove_pages`      |
| 米国       | `https://us.api.pdfblocks.com/v1/remove_pages`      |
| HIPAA 米国 | `https://hipaa.api.pdfblocks.com/v1/remove_pages`   |
| 欧州連合   | `https://eu.api.pdfblocks.com/v1/remove_pages`      |
| 英国       | `https://uk.api.pdfblocks.com/v1/remove_pages`      |
| カナダ     | `https://ca.api.pdfblocks.com/v1/remove_pages`      |
| オーストラリア | `https://au.api.pdfblocks.com/v1/remove_pages` |
| インド     | `https://in.api.pdfblocks.com/v1/remove_pages`      |
| ブラジル   | `https://br.api.pdfblocks.com/v1/remove_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="pages" type="string" required>
  削除するページを、[ページ範囲](#ページの選択)として `2,4..6` のように指定します。選択ですべてのページを対象にすることはできません。少なくとも1ページは残す必要があります。最大1000文字です。
</ParamField>

### ページの選択

`pages` パラメーターには、1から始まるページ番号と範囲をカンマ区切りで指定します。これは**集合**として扱われるため、順序や重複は無視され、残るページは元のドキュメントの順序を保ちます。

| パターン  | 削除されるページ                       |
| --------- | --------------------------------------- |
| `1`       | 最初のページのみ                       |
| `1..3,5`  | 1、2、3、5ページ                        |
| `2..`     | 2ページ目から最後まで                  |
| `..-2`    | 最初のページから、最後から2番目のページまで |
| `-1`      | 最後のページ                           |

完全なリファレンスについては、[ページの選択](/docs/api/selecting-pages)を参照してください。

<Note>
  選択は**集合**として扱われ、少なくとも1ページは残す必要があります。すべてのページを対象にした選択は `400` で拒否されます。
</Note>

## 例

ページ2と4〜6を PDF から削除します。

<CodeGroup>

```bash title="cURL"
curl https://api.pdfblocks.com/v1/remove_pages \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F pages='2,4..6' \
  -o trimmed.pdf
```

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

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

response.raise_for_status()
with open('trimmed.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('pages', '2,4..6');

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

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

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

$pdf = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200) {
    file_put_contents('trimmed.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/remove_pages', form: {
    file: HTTP::FormData::File.new('input.pdf'),
    pages: '2,4..6',
  })

File.write('trimmed.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("pages", "2,4..6")
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/remove_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("trimmed.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("2,4..6"), "pages" },
};

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

</CodeGroup>

## レスポンス

成功すると、レスポンスは `200 OK` となり、ボディにトリミングされた PDF が入ります。

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

残ったページは元の順序を保ちます。削除されるのは選択したページだけです。上記の例のように、ボディを直接ファイルへストリーミングしてください。当社側には何も保存されません。

## エラー

失敗したリクエストは `application/problem+json` 形式のボディを返します。このエンドポイントで最も多いのは `400` で、`pages` の形式が不正な場合や、すべてのページを削除することになる場合に返されます。`errors` オブジェクトには、フィールドごとの内容が示されます。

```json
{
  "type": "https://www.pdfblocks.com/docs/api/v1/error/400",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "errors": {
    "pages": ["At least one page must remain, so the selection cannot cover every page."]
  }
}
```

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

## バリエーション

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

<AccordionGroup>

<Accordion title="最後のページを削除">

<CodeGroup>

```bash title="cURL"
curl https://api.pdfblocks.com/v1/remove_pages \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F pages='-1' \
  -o without-last.pdf
```

```python title="Python"
import requests

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

response.raise_for_status()
with open('without-last.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('pages', '-1');

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

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

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

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

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

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

File.write('without-last.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("pages", "-1")
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/remove_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("without-last.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"), "pages" },
};

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

</CodeGroup>

</Accordion>

<Accordion title="表紙ページを削除">

<CodeGroup>

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

```python title="Python"
import requests

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

response.raise_for_status()
with open('no-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('pages', '1');

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

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

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

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

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

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

File.write('no-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("pages", "1")
	form.Close()

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

var response = await client.PostAsync(
    "https://api.pdfblocks.com/v1/remove_pages", form);
response.EnsureSuccessStatusCode();
await File.WriteAllBytesAsync(
    "no-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/reorder-pages-of-pdf">
  残ったページを並べ替えます。
</Card>

<Card title="ページを反転" href="/docs/api/reverse-pages-of-pdf">
  ページの順序を反転します。
</Card>

<Card title="ページを回転" href="/docs/api/rotate-pages-in-pdf">
  選択したページを回転します。
</Card>

</CardGroup>
