# Ajouter un filigrane image à un PDF

Apposez une image PNG ou JPEG sur les pages d’un PDF, avec le contrôle de la transparence, de la marge et des pages concernées.

Ajoutez un filigrane image à un document PDF. Fournissez un PNG ou un JPEG et
contrôlez sa transparence et sa marge. Par défaut, le filigrane est apposé sur
toutes les pages : utilisez le paramètre [`pages`](#sélectionner-des-pages) pour
cibler un sous-ensemble. L’API est *stateless* : votre document est traité dans
la région et n’est jamais stocké.

## Endpoint

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

Disponible dans toutes les régions. Consultez [Régions et résidence des
données](/docs/api/regions-and-data-residency) pour le routage et la résidence
des données.

| Région           | URL                                                      |
| ---------------- | -------------------------------------------------------- |
| Global           | `https://api.pdfblocks.com/v1/add_image_watermark`       |
| États-Unis       | `https://us.api.pdfblocks.com/v1/add_image_watermark`    |
| HIPAA États-Unis | `https://hipaa.api.pdfblocks.com/v1/add_image_watermark` |
| Union européenne | `https://eu.api.pdfblocks.com/v1/add_image_watermark`    |
| Royaume-Uni      | `https://uk.api.pdfblocks.com/v1/add_image_watermark`    |
| Canada           | `https://ca.api.pdfblocks.com/v1/add_image_watermark`    |
| Australie        | `https://au.api.pdfblocks.com/v1/add_image_watermark`    |
| Japon            | `https://jp.api.pdfblocks.com/v1/add_image_watermark`    |
| Inde             | `https://in.api.pdfblocks.com/v1/add_image_watermark`    |
| Brésil           | `https://br.api.pdfblocks.com/v1/add_image_watermark`    |

## Authentification

Authentifiez chaque requête avec votre clé d’API secrète dans l’en-tête
`X-API-Key`, en HTTPS. Créez et gérez vos clés depuis le
[dashboard](https://dashboard.pdfblocks.com). Consultez
[Authentification](/docs/api/authentication) pour plus de détails.

## Requête

L’endpoint accepte un corps de requête `multipart/form-data`.

<ParamField name="file" type="file" required>
  Le document PDF d’entrée.
</ParamField>

<ParamField name="image" type="file" required>
  L’image du filigrane à apposer sur chaque page. Doit être un PNG ou un JPEG.
  Consultez [Travailler avec les fichiers](/docs/api/working-with-files) pour
  savoir comment la joindre.
</ParamField>

<ParamField name="transparency" type="integer" default="50">
  Le niveau de transparence, de `0` (entièrement opaque) à `100` (entièrement
  transparent).
</ParamField>

<ParamField name="margin" type="decimal" default="1.0">
  La distance, en pouces, entre le bord de la page et le filigrane. `0` ou plus.
</ParamField>

<ParamField name="pages" type="string">
  Les pages sur lesquelles apposer le filigrane, écrites sous la forme d’une
  [plage de pages](#sélectionner-des-pages) telle que `1..3,5`. En cas
  d’omission, le filigrane est appliqué à toutes les pages. Maximum 1000
  caractères.
</ParamField>

### Sélectionner des pages

Le paramètre `pages` reçoit une liste, séparée par des virgules, de numéros de
page en base 1 et de plages. Il est traité comme un **ensemble** : l’ordre et
les doublons sont ignorés, et le filigrane est toujours apposé dans l’ordre du
document.

| Motif    | Sélectionne                            |
| -------- | -------------------------------------- |
| *(omis)* | Toutes les pages                       |
| `1`      | La première page uniquement            |
| `1..3,5` | Les pages 1, 2, 3 et 5                 |
| `2..`    | De la page 2 à la dernière page        |
| `..-2`   | De la première page à l’avant-dernière |
| `-1`     | La dernière page                       |

Consultez [Sélectionner des pages](/docs/api/selecting-pages) pour la référence
complète.

## Exemples

Apposez un logo sur toutes les pages avec 60 % de transparence :

<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 transparency=60 \
  -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={'transparency': 60},
    )

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('transparency', '60');

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()));
```

```php title="PHP"
<?php
$ch = curl_init('https://api.pdfblocks.com/v1/add_image_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'),
        'image' => new CURLFile('logo.png', 'image/png'),
        'transparency' => '60',
    ],
]);

$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_image_watermark', form: {
    file: HTTP::FormData::File.new('input.pdf'),
    image: HTTP::FormData::File.new('logo.png'),
    transparency: '60',
  })

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()
	filePart, _ := form.CreateFormFile("file", "input.pdf")
	io.Copy(filePart, file)

	image, _ := os.Open("logo.png")
	defer image.Close()
	imagePart, _ := form.CreateFormFile("image", "logo.png")
	io.Copy(imagePart, image)

	form.WriteField("transparency", "60")
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/add_image_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 ByteArrayContent(File.ReadAllBytes("logo.png")), "image", "logo.png" },
    { new StringContent("60"), "transparency" },
};

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

</CodeGroup>

## Réponse

En cas de succès, la réponse est `200 OK` avec le PDF filigrané comme corps :

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

La sortie conserve le nombre de pages et les dimensions du document d’entrée :
seul le filigrane est ajouté. Écrivez le corps directement dans un fichier,
comme le font les exemples ci-dessus ; rien n’est stocké de notre côté.

## Erreurs

Les requêtes en échec renvoient un corps `application/problem+json`. La plus
courante pour cet endpoint est une `400`, renvoyée lorsqu’un paramètre n’est pas
valide ou que `image` n’est pas dans un format pris en charge. L’objet `errors`
nomme chaque champ :

```json
{
  "type": "https://www.pdfblocks.com/docs/api/v1/error/400",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "errors": {
    "image": ["The image must be a PNG or JPEG file."]
  }
}
```

Une `X-API-Key` absente ou non valide renvoie une `401`. Consultez
[Erreurs](/docs/api/errors) pour tous les codes de statut et la forme complète
de la réponse.

## Recettes

Variantes courantes. Dépliez-en une pour la voir dans tous les langages.

<AccordionGroup>

<Accordion title="Un logo discret sur toutes les pages">

<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 transparency=85 \
  -o faint.pdf
```

```python title="Python"
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={'transparency': 85},
    )

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

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('faint.pdf', Buffer.from(await response.arrayBuffer()));
```

```php title="PHP"
<?php
$ch = curl_init('https://api.pdfblocks.com/v1/add_image_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'),
        'image' => new CURLFile('logo.png', 'image/png'),
        'transparency' => '85',
    ],
]);

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

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

response = HTTP
  .headers('X-API-Key' => 'your_api_key')
  .post('https://api.pdfblocks.com/v1/add_image_watermark', form: {
    file: HTTP::FormData::File.new('input.pdf'),
    image: HTTP::FormData::File.new('logo.png'),
    transparency: '85',
  })

File.write('faint.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()
	filePart, _ := form.CreateFormFile("file", "input.pdf")
	io.Copy(filePart, file)

	image, _ := os.Open("logo.png")
	defer image.Close()
	imagePart, _ := form.CreateFormFile("image", "logo.png")
	io.Copy(imagePart, image)

	form.WriteField("transparency", "85")
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/add_image_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("faint.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 ByteArrayContent(File.ReadAllBytes("logo.png")), "image", "logo.png" },
    { new StringContent("85"), "transparency" },
};

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

</CodeGroup>

</Accordion>

<Accordion title="Un logo sur la page de couverture uniquement">

<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 cover-stamped.pdf
```

```python title="Python"
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('cover-stamped.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('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('cover-stamped.pdf', Buffer.from(await response.arrayBuffer()));
```

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

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

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

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

File.write('cover-stamped.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()
	filePart, _ := form.CreateFormFile("file", "input.pdf")
	io.Copy(filePart, file)

	image, _ := os.Open("logo.png")
	defer image.Close()
	imagePart, _ := form.CreateFormFile("image", "logo.png")
	io.Copy(imagePart, image)

	form.WriteField("pages", "1")
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/add_image_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("cover-stamped.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 ByteArrayContent(File.ReadAllBytes("logo.png")), "image", "logo.png" },
    { new StringContent("1"), "pages" },
};

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

</CodeGroup>

</Accordion>

</AccordionGroup>

## Actions associées

<CardGroup cols={2}>

<Card title="Ajouter un filigrane texte" href="/docs/api/add-text-watermark-to-pdf">
  Apposez du texte plutôt qu’une image.
</Card>

<Card title="Ajouter un mot de passe" href="/docs/api/add-password-to-pdf">
  Chiffrez le document filigrané.
</Card>

<Card title="Fusionner des documents" href="/docs/api/merge-pdf-documents">
  Combinez des fichiers avant d’apposer le filigrane.
</Card>

<Card title="Extraire des pages" href="/docs/api/extract-pages-from-pdf">
  Récupérez les pages filigranées.
</Card>

</CardGroup>
