PDF Blocks
料金サポート
無料で始める
ページへ移動

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

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

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

pages セレクター

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

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

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

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

cURLbash
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
Pythonpython
# 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)
Node.jsjavascript
// 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()));
PHPphp
<?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);
}
Rubyruby
# 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?
Gogo
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)
}
C#csharp
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());

その他の指定パターン

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

表紙のみbash
# 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
# 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
# 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
# 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

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

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

cURLbash
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
Pythonpython
# 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)
Node.jsjavascript
// 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()));

同じ pages セレクターは、ページ操作系のアクションでも使われます。ページの抽出ページの削除ページの回転はいずれも同じ方法でこれを解釈します。一度覚えれば、どこでも使い回せます。

関連