# Apporre una filigrana su pagine specifiche

Come limitare una filigrana di testo o immagine a determinate pagine con il selettore pages, e gli schemi più frequenti.

Per impostazione predefinita una filigrana viene apposta su ogni pagina. Il
campo `pages` restringe la selezione a un sottoinsieme preciso (una pagina di
copertina, un’appendice, tutto tranne la prima pagina), così è possibile
apporla esattamente dove serve. Lo accettano sia [Aggiungere una filigrana di
testo](/docs/api/add-text-watermark-to-pdf) sia [Aggiungere una filigrana
immagine](/docs/api/add-image-watermark-to-pdf), e funziona allo stesso modo in
ogni azione che accetta un campo `pages`.

## Il selettore `pages`

`pages` è un elenco di numeri di pagina in base 1 e di intervalli, separati da
virgole. È trattato come un **insieme**: l’ordine e i duplicati vengono
ignorati e la filigrana viene sempre apposta seguendo l’ordine del documento.
Ometterlo seleziona tutte le pagine. Vedere [Selezionare le
pagine](/docs/api/selecting-pages) per la sintassi completa.

| Obiettivo | Valore di `pages` |
| --- | --- |
| Solo la pagina di copertina | `1` |
| Tutte le pagine tranne la prima | `2..` |
| Tutte le pagine tranne l’ultima | `..-2` |
| Solo l’ultima pagina | `-1` |
| Un’appendice dalla pagina 8 in poi | `8..` |
| Un insieme specifico di pagine | `1..3,5` |
| Le ultime tre pagine | `-3..-1` |

## Apporre la filigrana su tutte le pagine tranne la copertina

Una richiesta frequente: una dicitura di riservatezza ripetuta sul corpo di un
documento, ma non sulla pagina del titolo. Selezionare `pages=2..`, dalla
pagina 2 all’ultima pagina.

<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>

## Altri schemi di selezione

L’unica cosa che cambia tra questi esempi è il valore di `pages`. Ciascuno
scrive in un file di output diverso.

<CodeGroup>

```bash title="Solo la pagina di copertina"
# 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="Tutte le pagine tranne l’ultima"
# 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="Dall’appendice in poi"
# 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="Pagine selezionate"
# 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>

## Le filigrane immagine si applicano alle pagine allo stesso modo

Una filigrana immagine utilizza un campo `pages` identico: basta passare un PNG
o un JPEG nel campo `image` insieme a `file`. Questo esempio appone un logo
solo sulla pagina di copertina:

<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>
  Lo stesso selettore `pages` guida anche le azioni orientate alle pagine:
  [Estrarre pagine](/docs/api/extract-pages-from-pdf), [Rimuovere
  pagine](/docs/api/remove-pages-from-pdf) e [Ruotare
  pagine](/docs/api/rotate-pages-in-pdf) lo leggono tutte allo stesso modo. Lo
  si impara una volta e lo si riutilizza ovunque.
</Tip>

## Vedi anche

<CardGroup cols={2}>

<Card title="Selezionare le pagine" href="/docs/api/selecting-pages">
  La sintassi completa degli intervalli di pagine, indici negativi compresi.
</Card>

<Card title="Aggiungere una filigrana di testo" href="/docs/api/add-text-watermark-to-pdf">
  Modelli, colori, opacità e margini.
</Card>

<Card title="Aggiungere una filigrana immagine" href="/docs/api/add-image-watermark-to-pdf">
  Apporre un logo PNG o JPEG al posto del testo.
</Card>

<Card title="Estrarre pagine" href="/docs/api/extract-pages-from-pdf">
  Ricavare un sottoinsieme di pagine con lo stesso selettore.
</Card>

</CardGroup>
