PDF Blocks
PrezziSupporto
Iniziare gratis
Aprire la pagina

Aggiungere una filigrana di testo a un PDF

Apporre fino a tre righe di testo sulle pagine di un PDF, con il controllo su modello, colore e opacità.

Aggiungere una filigrana di testo a un documento PDF. È possibile fornire fino a tre righe di testo e controllare il modello, il colore, 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_text_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_text_watermark
Stati Uniti https://us.api.pdfblocks.com/v1/add_text_watermark
HIPAA Stati Uniti https://hipaa.api.pdfblocks.com/v1/add_text_watermark
Unione europea https://eu.api.pdfblocks.com/v1/add_text_watermark
Regno Unito https://uk.api.pdfblocks.com/v1/add_text_watermark
Canada https://ca.api.pdfblocks.com/v1/add_text_watermark
Australia https://au.api.pdfblocks.com/v1/add_text_watermark
Giappone https://jp.api.pdfblocks.com/v1/add_text_watermark
India https://in.api.pdfblocks.com/v1/add_text_watermark
Brasile https://br.api.pdfblocks.com/v1/add_text_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.

line_1stringrequired

La prima riga di testo della filigrana. Massimo 32 caratteri. Utilizzare caratteri latini standard.

line_2string

La seconda riga di testo della filigrana. Massimo 32 caratteri.

line_3string

La terza riga di testo della filigrana. Massimo 32 caratteri.

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.

templateintegerdefault:1001

Il modello della filigrana, che ne imposta lo stile (pieno o contorno) e l’orientamento.

colorstringdefault:Gray

Il colore della filigrana. Uno tra Red, Blue, Gray e Black.

transparencyintegerdefault:75

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.

Modelli di filigrana

Ogni template combina uno stile (pieno o contorno) con un orientamento. Passare l’ID al parametro template.

Modello Stile Orientamento
1001 Pieno Diagonale, dal basso a sinistra verso l’alto a destra (predefinito)
1002 Pieno Diagonale, dall’alto a sinistra verso il basso a destra
1003 Pieno Orizzontale
1004 Pieno Verticale, letta dal basso verso l’alto
1005 Pieno Verticale, letta dall’alto verso il basso
1017 Contorno Diagonale, dal basso a sinistra verso l’alto a destra
1018 Contorno Diagonale, dall’alto a sinistra verso il basso a destra
1019 Contorno Orizzontale
1020 Contorno Verticale, letta dal basso verso l’alto
1021 Contorno Verticale, letta dall’alto verso il basso

Tutti i modelli sono mostrati su una pagina di esempio nel catalogo visivo dei modelli.

Colori

Valore Campione
Red #C00000
Blue #005DFF
Gray #545454
Black #000000

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 una filigrana di due righe sulle pagine da 1 a 3 e sulla pagina 5:

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 line_2='ACME, Inc.' \
  -F template=1001 \
  -F color=Red \
  -F pages='1..3,5' \
  -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',
            'line_2': 'ACME, Inc.',
            'template': 1001,
            'color': 'Red',
            'pages': '1..3,5',
        },
    )

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('line_2', 'ACME, Inc.');
body.set('template', '1001');
body.set('color', 'Red');
body.set('pages', '1..3,5');

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',
        'line_2' => 'ACME, Inc.',
        'template' => '1001',
        'color' => 'Red',
        'pages' => '1..3,5',
    ],
]);

$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',
    line_2: 'ACME, Inc.',
    template: '1001',
    color: 'Red',
    pages: '1..3,5',
  })

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("line_2", "ACME, Inc.")
	form.WriteField("template", "1001")
	form.WriteField("color", "Red")
	form.WriteField("pages", "1..3,5")
	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("ACME, Inc."), "line_2" },
    { new StringContent("1001"), "template" },
    { new StringContent("Red"), "color" },
    { new StringContent("1..3,5"), "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());

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

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 file non è un PDF leggibile. 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": {
    "line_1": ["The field line_1 must be a string with a maximum length of 32."]
  }
}

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 DRAFT rosso e ben visibile su tutte le pagine
cURLbash
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 color=Red \
  -F template=1001 \
  -F transparency=40 \
  -o draft.pdf
Pythonpython
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': 'DRAFT', 'color': 'Red', 'template': 1001, 'transparency': 40},
    )

response.raise_for_status()
with open('draft.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('line_1', 'DRAFT');
body.set('color', 'Red');
body.set('template', '1001');
body.set('transparency', '40');

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('draft.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' => 'DRAFT',
        'color' => 'Red',
        'template' => '1001',
        'transparency' => '40',
    ],
]);

$pdf = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200) {
    file_put_contents('draft.pdf', $pdf);
}
Rubyruby
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: 'DRAFT',
    color: 'Red',
    template: '1001',
    transparency: '40',
  })

File.write('draft.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", "DRAFT")
	form.WriteField("color", "Red")
	form.WriteField("template", "1001")
	form.WriteField("transparency", "40")
	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("draft.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("DRAFT"), "line_1" },
    { new StringContent("Red"), "color" },
    { new StringContent("1001"), "template" },
    { new StringContent("40"), "transparency" },
};

var response = await client.PostAsync(
    "https://api.pdfblocks.com/v1/add_text_watermark", form);
response.EnsureSuccessStatusCode();
await File.WriteAllBytesAsync(
    "draft.pdf", await response.Content.ReadAsByteArrayAsync());
Un CONFIDENTIAL con contorno sulla pagina di copertina
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 template=1017 \
  -F pages='1' \
  -o confidential.pdf
Pythonpython
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', 'template': 1017, 'pages': '1'},
    )

response.raise_for_status()
with open('confidential.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('line_1', 'CONFIDENTIAL');
body.set('template', '1017');
body.set('pages', '1');

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('confidential.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',
        'template' => '1017',
        'pages' => '1',
    ],
]);

$pdf = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200) {
    file_put_contents('confidential.pdf', $pdf);
}
Rubyruby
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',
    template: '1017',
    pages: '1',
  })

File.write('confidential.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("template", "1017")
	form.WriteField("pages", "1")
	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("confidential.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("1017"), "template" },
    { new StringContent("1"), "pages" },
};

var response = await client.PostAsync(
    "https://api.pdfblocks.com/v1/add_text_watermark", form);
response.EnsureSuccessStatusCode();
await File.WriteAllBytesAsync(
    "confidential.pdf", await response.Content.ReadAsByteArrayAsync());
Una nota grigia discreta su tutte le pagine tranne l’ultima
cURLbash
curl https://api.pdfblocks.com/v1/add_text_watermark \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F line_1='ACME, Inc.' \
  -F line_2='Do not distribute' \
  -F color=Gray \
  -F transparency=88 \
  -F pages='..-2' \
  -o notice.pdf
Pythonpython
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': 'ACME, Inc.',
            'line_2': 'Do not distribute',
            'color': 'Gray',
            'transparency': 88,
            'pages': '..-2',
        },
    )

response.raise_for_status()
with open('notice.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('line_1', 'ACME, Inc.');
body.set('line_2', 'Do not distribute');
body.set('color', 'Gray');
body.set('transparency', '88');
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('notice.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' => 'ACME, Inc.',
        'line_2' => 'Do not distribute',
        'color' => 'Gray',
        'transparency' => '88',
        'pages' => '..-2',
    ],
]);

$pdf = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200) {
    file_put_contents('notice.pdf', $pdf);
}
Rubyruby
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: 'ACME, Inc.',
    line_2: 'Do not distribute',
    color: 'Gray',
    transparency: '88',
    pages: '..-2',
  })

File.write('notice.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", "ACME, Inc.")
	form.WriteField("line_2", "Do not distribute")
	form.WriteField("color", "Gray")
	form.WriteField("transparency", "88")
	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("notice.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("ACME, Inc."), "line_1" },
    { new StringContent("Do not distribute"), "line_2" },
    { new StringContent("Gray"), "color" },
    { new StringContent("88"), "transparency" },
    { new StringContent("..-2"), "pages" },
};

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

Azioni correlate