PDF Blocks
PrezziSupporto
Iniziare gratis
Aprire la pagina

Aggiungere una filigrana immagine a un PDF

Apporre un’immagine PNG o JPEG sulle pagine di un PDF, con il controllo su trasparenza, margine e pagine interessate.

Aggiungere una filigrana immagine a un documento PDF. È possibile fornire un PNG o un JPEG e controllarne la trasparenza e il margine. Per impostazione predefinita la filigrana viene apposta su ogni pagina. Utilizzare il parametro pages per applicarla solo a un sottoinsieme. L’API è stateless: il documento viene elaborato nella sua regione e non viene mai memorizzato.

Endpoint

POST
/v1/add_image_watermark

Disponibile in tutte le regioni. Vedere Regioni e residenza dei dati per il routing e la residenza dei dati.

Regione URL
Globale https://api.pdfblocks.com/v1/add_image_watermark
Stati Uniti https://us.api.pdfblocks.com/v1/add_image_watermark
HIPAA Stati Uniti https://hipaa.api.pdfblocks.com/v1/add_image_watermark
Unione europea https://eu.api.pdfblocks.com/v1/add_image_watermark
Regno Unito https://uk.api.pdfblocks.com/v1/add_image_watermark
Canada https://ca.api.pdfblocks.com/v1/add_image_watermark
Australia https://au.api.pdfblocks.com/v1/add_image_watermark
Giappone https://jp.api.pdfblocks.com/v1/add_image_watermark
India https://in.api.pdfblocks.com/v1/add_image_watermark
Brasile https://br.api.pdfblocks.com/v1/add_image_watermark

Autenticazione

Autenticare ogni richiesta con la chiave API segreta nell’intestazione X-API-Key, su HTTPS. Le chiavi si creano e si gestiscono dalla dashboard. Vedere Autenticazione per i dettagli.

Richiesta

L’endpoint accetta un corpo della richiesta multipart/form-data.

filefilerequired

Il documento PDF di input.

imagefilerequired

L’immagine della filigrana da apporre su ogni pagina. Deve essere un PNG o un JPEG. Vedere Lavorare con i file per sapere come allegarla.

transparencyintegerdefault:50

Il livello di trasparenza, da 0 (del tutto opaco) a 100 (del tutto trasparente).

margindecimaldefault:1.0

La distanza, in pollici, dal bordo della pagina alla filigrana. 0 o superiore.

pagesstring

Le pagine su cui apporre la filigrana, scritte come intervallo di pagine, ad esempio 1..3,5. Se omesso, la filigrana viene applicata a ogni pagina. Massimo 1000 caratteri.

Selezionare le pagine

Il parametro pages accetta 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.

Schema Seleziona
(omesso) Tutte le pagine
1 Solo la prima pagina
1..3,5 Le pagine 1, 2, 3 e 5
2.. Dalla pagina 2 all’ultima pagina
..-2 Dalla prima pagina alla penultima
-1 L’ultima pagina

Vedere Selezionare le pagine per il riferimento completo.

Esempi

Apporre un logo su ogni pagina con una trasparenza del 60%:

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

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('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()));
PHPphp
<?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);
}
Rubyruby
# 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?
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()
	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)
}
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 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());

Risposta

In caso di successo, la risposta è 200 OK con il PDF filigranato come corpo:

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

L’output conserva il numero di pagine e le dimensioni dell’input: viene aggiunta soltanto la filigrana. Scrivere il corpo direttamente in un file, come fanno gli esempi qui sopra: nulla viene memorizzato dalla nostra parte.

Errori

Le richieste non riuscite restituiscono un corpo application/problem+json. L’errore più comune per questo endpoint è un 400, restituito quando un parametro non è valido oppure image non è in un formato supportato. L’oggetto errors indica ogni campo:

{
  "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."]
  }
}

Un X-API-Key mancante o non valido restituisce un 401. Vedere Errori per tutti i codici di stato e la forma completa della risposta.

Ricette

Varianti comuni. Espandere una voce per vederla in tutti i linguaggi.

Un logo tenue su tutte le pagine
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 transparency=85 \
  -o faint.pdf
Pythonpython
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)
Node.jsjavascript
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()));
PHPphp
<?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);
}
Rubyruby
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?
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()
	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)
}
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 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());
Un logo solo sulla pagina di copertina
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 cover-stamped.pdf
Pythonpython
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)
Node.jsjavascript
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()));
PHPphp
<?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);
}
Rubyruby
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?
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()
	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)
}
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 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());

Azioni correlate