# 特定のページに透かしを付与する

`pages` セレクターを使ってテキストまたは画像の透かしを特定のページに限定する方法と、よく使われるパターンを紹介します。

デフォルトでは、透かしはすべてのページに付与されます。`pages` フィールドを使うと、これを正確なページの部分集合（表紙、付録、最初のページ以外のすべてなど）に絞り込めるため、必要な場所だけに透かしを付与できます。[テキスト透かしの追加](/docs/api/add-text-watermark-to-pdf) と[画像透かしの追加](/docs/api/add-image-watermark-to-pdf)はどちらもこのフィールドに対応しており、`pages` フィールドを持つすべてのアクションで同じように機能します。

## `pages` セレクター

`pages` は、1から始まるページ番号と範囲をカンマ区切りで指定するフィールドです。これは **集合**として扱われるため、順序や重複は無視され、ページは常にドキュメントの順序で透かしが付与されます。省略するとすべてのページが選択されます。完全な構文については[ページの選択](/docs/api/selecting-pages)を参照してください。

| 目的 | `pages` の値 |
| --- | --- |
| 表紙のみ | `1` |
| 最初のページ以外のすべて | `2..` |
| 最後のページ以外のすべて | `..-2` |
| 最後のページのみ | `-1` |
| ページ8以降の付録 | `8..` |
| 特定のページの集合 | `1..3,5` |
| 最後の3ページ | `-3..-1` |

## 表紙を除くすべてのページに透かしを付与する

よくある要望として、タイトルページを除くドキュメント本文全体に、繰り返しの機密マークを入れたい場合があります。`pages=2..` を指定すると、ページ2から最後のページまでが対象になります。

<CodeGroup>

```bash title="cURL"
curl https://api.pdfblocks.com/v1/add_text_watermark \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F line_1='CONFIDENTIAL' \
  -F pages='2..' \
  -o watermarked.pdf
```

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

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

response.raise_for_status()
with open('watermarked.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('line_1', 'CONFIDENTIAL');
body.set('pages', '2..');

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

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

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

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

File.write('watermarked.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("line_1", "CONFIDENTIAL")
	form.WriteField("pages", "2..")
	form.Close()

	req, _ := http.NewRequest("POST",
		"https://api.pdfblocks.com/v1/add_text_watermark", &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("watermarked.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("CONFIDENTIAL"), "line_1" },
    { new StringContent("2.."), "pages" },
};

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

</CodeGroup>

## その他の指定パターン

これらの例で変わるのは `pages` の値だけです。各スニペットはそれぞれ異なる出力ファイルに書き込みます。

<CodeGroup>

```bash title="表紙のみ"
# pages=1: stamp just the title page.
curl https://api.pdfblocks.com/v1/add_text_watermark \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F line_1='DRAFT' \
  -F pages='1' \
  -o cover.pdf
```

```bash title="最後のページ以外のすべて"
# pages=..-2: the first page through the second-to-last.
curl https://api.pdfblocks.com/v1/add_text_watermark \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F line_1='DO NOT DISTRIBUTE' \
  -F pages='..-2' \
  -o body.pdf
```

```bash title="付録以降"
# pages=8..: page 8 to the end.
curl https://api.pdfblocks.com/v1/add_text_watermark \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F line_1='APPENDIX' \
  -F pages='8..' \
  -o appendix.pdf
```

```bash title="選択したページ"
# pages=1..3,5: pages 1, 2, 3, and 5.
curl https://api.pdfblocks.com/v1/add_text_watermark \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F line_1='REVIEW COPY' \
  -F pages='1..3,5' \
  -o review.pdf
```

</CodeGroup>

## 画像透かしも同じ方法で対象ページを指定する

画像透かしも `pages` フィールドの扱いは同じです。`file` と一緒に `image` フィールドへ PNG または JPEG を渡します。次の例では、表紙のみにロゴを付与します。

<CodeGroup>

```bash title="cURL"
curl https://api.pdfblocks.com/v1/add_image_watermark \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F image=@logo.png \
  -F pages='1' \
  -o watermarked.pdf
```

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

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

response.raise_for_status()
with open('watermarked.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('image', new Blob([await readFile('logo.png')]), 'logo.png');
body.set('pages', '1');

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

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

</CodeGroup>

<Tip>
  同じ `pages` セレクターは、ページ操作系のアクションでも使われます。[ページの抽出](/docs/api/extract-pages-from-pdf)、[ページの削除](/docs/api/remove-pages-from-pdf)、[ページの回転](/docs/api/rotate-pages-in-pdf)はいずれも同じ方法でこれを解釈します。一度覚えれば、どこでも使い回せます。
</Tip>

## 関連

<CardGroup cols={2}>

<Card title="ページの選択" href="/docs/api/selecting-pages">
  負のインデックスを含む、ページ範囲の完全な構文です。
</Card>

<Card title="テキスト透かしの追加" href="/docs/api/add-text-watermark-to-pdf">
  テンプレート、色、不透明度、余白です。
</Card>

<Card title="画像透かしの追加" href="/docs/api/add-image-watermark-to-pdf">
  テキストの代わりに PNG または JPEG のロゴを付与します。
</Card>

<Card title="ページを抽出する" href="/docs/api/extract-pages-from-pdf">
  同じセレクターでページの部分集合を抽出します。
</Card>

</CardGroup>
