PDF Blocks
PreciosSoporte
Empezar gratis
Ir a la página

Añadir una marca de agua de imagen a un PDF

Estampe una imagen PNG o JPEG en las páginas de un PDF, con control de la transparencia, el margen y las páginas que la reciben.

Añada una marca de agua de imagen a un documento PDF. Proporcione un PNG o un JPEG y controle su transparencia y su margen. De forma predeterminada, la marca de agua se estampa en todas las páginas: use el parámetro pages para apuntar a un subconjunto. La API es stateless: su documento se procesa en la región y nunca se almacena.

Endpoint

POST
/v1/add_image_watermark

Disponible en todas las regiones. Consulte Regiones y residencia de datos para el enrutamiento y la residencia de datos.

Región URL
Global https://api.pdfblocks.com/v1/add_image_watermark
Estados Unidos https://us.api.pdfblocks.com/v1/add_image_watermark
HIPAA de EE. UU. https://hipaa.api.pdfblocks.com/v1/add_image_watermark
Unión Europea https://eu.api.pdfblocks.com/v1/add_image_watermark
Reino Unido https://uk.api.pdfblocks.com/v1/add_image_watermark
Canadá https://ca.api.pdfblocks.com/v1/add_image_watermark
Australia https://au.api.pdfblocks.com/v1/add_image_watermark
Japón https://jp.api.pdfblocks.com/v1/add_image_watermark
India https://in.api.pdfblocks.com/v1/add_image_watermark
Brasil https://br.api.pdfblocks.com/v1/add_image_watermark

Autenticación

Autentique cada solicitud con su clave de API secreta en la cabecera X-API-Key, por HTTPS. Cree y administre sus claves desde el dashboard. Consulte Autenticación para más detalles.

Solicitud

El endpoint acepta un cuerpo de solicitud multipart/form-data.

filefilerequired

El documento PDF de entrada.

imagefilerequired

La imagen de la marca de agua que se estampará en cada página. Debe ser PNG o JPEG. Consulte Trabajar con archivos para saber cómo adjuntarla.

transparencyintegerdefault:50

El nivel de transparencia, de 0 (totalmente opaco) a 100 (totalmente transparente).

margindecimaldefault:1.0

La distancia, en pulgadas, del borde de la página a la marca de agua. 0 o mayor.

pagesstring

Las páginas que se estamparán, escritas como un rango de páginas tipo 1..3,5. Si se omite, la marca de agua se aplica a todas las páginas. Máximo 1000 caracteres.

Seleccionar páginas

El parámetro pages recibe una lista separada por comas de números de página en base 1 y de rangos. Se trata como un conjunto: el orden y los duplicados se ignoran, y las páginas siempre se estampan en el orden del documento.

Patrón Selecciona
(omitir) Todas las páginas
1 Solo la primera página
1..3,5 Las páginas 1, 2, 3 y 5
2.. De la página 2 a la última
..-2 De la primera página a la penúltima
-1 La última página

Consulte Seleccionar páginas para ver la referencia completa.

Ejemplos

Estampe un logotipo en todas las páginas con un 60 % de transparencia:

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

Respuesta

Si todo va bien, la respuesta es 200 OK con el PDF estampado como cuerpo:

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

La salida conserva el número de páginas y las dimensiones de la entrada: lo único que se añade es la marca de agua. Escriba el cuerpo directamente en un archivo, como hacen los ejemplos anteriores; en nuestro lado no se almacena nada.

Errores

Las solicitudes fallidas devuelven un cuerpo application/problem+json. El error más habitual en este endpoint es un 400, que se devuelve cuando un parámetro no es válido o image no tiene un formato admitido: el objeto errors nombra cada 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."]
  }
}

Una X-API-Key ausente o no válida devuelve un 401. Consulte Errores para ver todos los códigos de estado y la forma completa de la respuesta.

Recetas

Variantes habituales. Despliegue una para verla en todos los lenguajes.

Un logotipo tenue en todas las páginas
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 logotipo solo en la portada
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());

Acciones relacionadas