Marcas de agua en páginas concretas
Cómo limitar una marca de agua de texto o de imagen a determinadas páginas con el selector pages, y los patrones más habituales.
De forma predeterminada, una marca de agua cae en todas las páginas. El campo
pages lo reduce a un subconjunto preciso, ya sea una portada, un anexo o
todo menos la primera página, para que estampe exactamente donde hace falta.
Tanto Añadir marca de agua de texto
como Añadir marca de agua de imagen
lo aceptan, y funciona igual en todas las acciones que reciben un campo
pages.
El selector pages
pages es 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. Omitirlo
selecciona todas las páginas. Consulte Seleccionar
páginas para ver la sintaxis completa.
| Objetivo | Valor de pages |
|---|---|
| Solo la portada | 1 |
| Todas las páginas menos la primera | 2.. |
| Todas las páginas menos la última | ..-2 |
| Solo la última página | -1 |
| Un anexo a partir de la página 8 | 8.. |
| Un conjunto concreto de páginas | 1..3,5 |
| Las últimas tres páginas | -3..-1 |
Estampar todas las páginas menos la portada
Una petición habitual: una marca de confidencialidad continua en el cuerpo de
un documento, pero no sobre la portada. Seleccione pages=2.., de la página
2 a la última.
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# 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)// 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
$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);
}# 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?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)
}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());Más patrones de selección
Lo único que cambia entre estos es el valor de pages. Cada fragmento
escribe en un archivo de salida distinto.
# 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# 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# 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# 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.pdfLas marcas de agua de imagen se dirigen igual
Una marca de agua de imagen usa un campo pages idéntico: pase un PNG o un
JPEG en el campo image junto con file. Esto estampa un logotipo solo en
la portada:
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# 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)// 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()));El mismo selector pages gobierna también las acciones orientadas a
páginas: Extraer páginas, Quitar
páginas y Girar
páginas lo leen igual. Apréndalo una vez y
reutilícelo en todas partes.
Relacionado
La sintaxis completa de rangos de páginas, incluidos los índices negativos.
Plantillas, colores, opacidad y márgenes.
Estampe un logotipo PNG o JPEG en lugar de texto.
Extraiga un subconjunto de páginas con el mismo selector.