PDF Blocks
PreciosSoporte
Empezar gratis
Ir a la página

Añadir restricciones a un PDF

Establezca los indicadores de permiso de un PDF, controlando la copia, la impresión, la edición y el relleno de formularios, tras una contraseña de propietario.

Aplique restricciones de permiso a un PDF, limitando la copia, la impresión, la edición, el relleno de formularios y más, todo respaldado por una owner_password. Las restricciones son indicadores de permiso, algo distinto de añadir una contraseña, que establece la contraseña necesaria solo para abrir el archivo; aquí también puede establecer una user_password para exigir las dos cosas. La API es stateless: su documento se procesa en la región y nunca se almacena.

Endpoint

POST
/v1/add_restrictions

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_restrictions
Estados Unidos https://us.api.pdfblocks.com/v1/add_restrictions
HIPAA de EE. UU. https://hipaa.api.pdfblocks.com/v1/add_restrictions
Unión Europea https://eu.api.pdfblocks.com/v1/add_restrictions
Reino Unido https://uk.api.pdfblocks.com/v1/add_restrictions
Canadá https://ca.api.pdfblocks.com/v1/add_restrictions
Australia https://au.api.pdfblocks.com/v1/add_restrictions
Japón https://jp.api.pdfblocks.com/v1/add_restrictions
India https://in.api.pdfblocks.com/v1/add_restrictions
Brasil https://br.api.pdfblocks.com/v1/add_restrictions

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.

owner_passwordstringrequired

La contraseña de propietario. De 4 a 32 caracteres ASCII imprimibles. Abre el documento y cambia sus indicadores de permiso.

user_passwordstring

Una contraseña de usuario opcional. De 4 a 32 caracteres ASCII imprimibles. Si se establece, el documento no se puede abrir sin ella. Omítala, o déjela vacía, para que cualquiera pueda abrir el documento.

encryption_algorithmstringdefault:AES-128

El algoritmo de cifrado. Uno de AES-128 o AES-256.

allow_copy_contentbooleandefault:true

Permitir copiar texto e imágenes al portapapeles.

allow_change_contentbooleandefault:true

Permitir cambiar el contenido del documento.

allow_printbooleandefault:true

Permitir imprimir el documento.

allow_print_high_resolutionbooleandefault:true

Permitir imprimir en alta resolución.

allow_comment_and_fill_formbooleandefault:true

Permitir añadir, editar o modificar anotaciones y rellenar campos de formulario.

allow_fill_formbooleandefault:true

Permitir rellenar campos de formulario.

allow_assemble_documentbooleandefault:true

Permitir ensamblar o manipular el documento (insertar, eliminar y girar páginas).

allow_accessibilitybooleandefault:true

Permitir que el software de accesibilidad lea el texto y las imágenes del documento.

Indicadores de permiso

Cada indicador gobierna una acción que puede realizar el lector. Pase el indicador como booleano; póngalo en false para desactivar ese permiso.

Indicador Predeterminado Ponga false para…
allow_copy_content true bloquear la copia de texto e imágenes al portapapeles
allow_change_content true bloquear los cambios en el contenido del documento
allow_print true bloquear la impresión del documento
allow_print_high_resolution true bloquear la impresión en alta resolución
allow_comment_and_fill_form true bloquear añadir, editar o modificar anotaciones y rellenar campos de formulario
allow_fill_form true bloquear el relleno de campos de formulario
allow_assemble_document true bloquear el ensamblado o la manipulación del documento (insertar, eliminar y girar páginas)
allow_accessibility true bloquear que el software de accesibilidad lea el documento

Todos los indicadores valen true de forma predeterminada, así que nada queda restringido salvo que lo indique: envíe solo los indicadores que quiera desactivar. Las restricciones las hace cumplir la owner_password: un lector que la proporcione puede cambiar los permisos. Añada una user_password solo si también quiere pedir una contraseña para abrir el archivo. Para ver el ciclo completo, consulte Proteger documentos.

Ejemplos

Blinde un documento para que no se pueda copiar ni imprimir, dejando que cualquiera lo abra:

cURLbash
curl https://api.pdfblocks.com/v1/add_restrictions \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F owner_password='s3cr3t-owner' \
  -F allow_copy_content=false \
  -F allow_print=false \
  -F allow_print_high_resolution=false \
  -o restricted.pdf
Pythonpython
# pip install requests
import requests

with open('input.pdf', 'rb') as file:
    response = requests.post(
        'https://api.pdfblocks.com/v1/add_restrictions',
        headers={'X-API-Key': 'your_api_key'},
        files={'file': file},
        data={
            'owner_password': 's3cr3t-owner',
            'allow_copy_content': 'false',
            'allow_print': 'false',
            'allow_print_high_resolution': 'false',
        },
    )

response.raise_for_status()
with open('restricted.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('owner_password', 's3cr3t-owner');
body.set('allow_copy_content', 'false');
body.set('allow_print', 'false');
body.set('allow_print_high_resolution', 'false');

const response = await fetch('https://api.pdfblocks.com/v1/add_restrictions', {
  method: 'POST',
  headers: { 'X-API-Key': 'your_api_key' },
  body,
});

if (!response.ok) throw new Error(`Request failed: ${response.status}`);
await writeFile('restricted.pdf', Buffer.from(await response.arrayBuffer()));
PHPphp
<?php
$ch = curl_init('https://api.pdfblocks.com/v1/add_restrictions');
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'),
        'owner_password' => 's3cr3t-owner',
        'allow_copy_content' => 'false',
        'allow_print' => 'false',
        'allow_print_high_resolution' => 'false',
    ],
]);

$pdf = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200) {
    file_put_contents('restricted.pdf', $pdf);
}
Rubyruby
# gem install http
require 'http'

response = HTTP
  .headers('X-API-Key' => 'your_api_key')
  .post('https://api.pdfblocks.com/v1/add_restrictions', form: {
    file: HTTP::FormData::File.new('input.pdf'),
    owner_password: 's3cr3t-owner',
    allow_copy_content: 'false',
    allow_print: 'false',
    allow_print_high_resolution: 'false',
  })

File.write('restricted.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("owner_password", "s3cr3t-owner")
	form.WriteField("allow_copy_content", "false")
	form.WriteField("allow_print", "false")
	form.WriteField("allow_print_high_resolution", "false")
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/add_restrictions", &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("restricted.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("s3cr3t-owner"), "owner_password" },
    { new StringContent("false"), "allow_copy_content" },
    { new StringContent("false"), "allow_print" },
    { new StringContent("false"), "allow_print_high_resolution" },
};

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

Respuesta

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

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

La salida es el mismo documento con los permisos solicitados aplicados: sus páginas y su contenido no cambian. 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, por ejemplo una owner_password que no tiene entre 4 y 32 caracteres ASCII imprimibles, con el objeto errors nombrando cada campo:

{
  "type": "https://www.pdfblocks.com/docs/api/v1/error/400",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "errors": {
    "owner_password": ["The field owner_password must match the regular expression '^[\\x20-\\x7e]{4,32}$'."]
  }
}

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.

Solo lectura: bloquear la copia, la edición y la impresión
cURLbash
curl https://api.pdfblocks.com/v1/add_restrictions \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F owner_password='s3cr3t-owner' \
  -F allow_copy_content=false \
  -F allow_change_content=false \
  -F allow_print=false \
  -F allow_print_high_resolution=false \
  -o readonly.pdf
Pythonpython
import requests

with open('input.pdf', 'rb') as file:
    response = requests.post(
        'https://api.pdfblocks.com/v1/add_restrictions',
        headers={'X-API-Key': 'your_api_key'},
        files={'file': file},
        data={
            'owner_password': 's3cr3t-owner',
            'allow_copy_content': 'false',
            'allow_change_content': 'false',
            'allow_print': 'false',
            'allow_print_high_resolution': 'false',
        },
    )

response.raise_for_status()
with open('readonly.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('owner_password', 's3cr3t-owner');
body.set('allow_copy_content', 'false');
body.set('allow_change_content', 'false');
body.set('allow_print', 'false');
body.set('allow_print_high_resolution', 'false');

const response = await fetch('https://api.pdfblocks.com/v1/add_restrictions', {
  method: 'POST',
  headers: { 'X-API-Key': 'your_api_key' },
  body,
});

if (!response.ok) throw new Error(`Request failed: ${response.status}`);
await writeFile('readonly.pdf', Buffer.from(await response.arrayBuffer()));
PHPphp
<?php
$ch = curl_init('https://api.pdfblocks.com/v1/add_restrictions');
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'),
        'owner_password' => 's3cr3t-owner',
        'allow_copy_content' => 'false',
        'allow_change_content' => 'false',
        'allow_print' => 'false',
        'allow_print_high_resolution' => 'false',
    ],
]);

$pdf = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200) {
    file_put_contents('readonly.pdf', $pdf);
}
Rubyruby
require 'http'

response = HTTP
  .headers('X-API-Key' => 'your_api_key')
  .post('https://api.pdfblocks.com/v1/add_restrictions', form: {
    file: HTTP::FormData::File.new('input.pdf'),
    owner_password: 's3cr3t-owner',
    allow_copy_content: 'false',
    allow_change_content: 'false',
    allow_print: 'false',
    allow_print_high_resolution: 'false',
  })

File.write('readonly.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("owner_password", "s3cr3t-owner")
	form.WriteField("allow_copy_content", "false")
	form.WriteField("allow_change_content", "false")
	form.WriteField("allow_print", "false")
	form.WriteField("allow_print_high_resolution", "false")
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/add_restrictions", &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("readonly.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("s3cr3t-owner"), "owner_password" },
    { new StringContent("false"), "allow_copy_content" },
    { new StringContent("false"), "allow_change_content" },
    { new StringContent("false"), "allow_print" },
    { new StringContent("false"), "allow_print_high_resolution" },
};

var response = await client.PostAsync(
    "https://api.pdfblocks.com/v1/add_restrictions", form);
response.EnsureSuccessStatusCode();
await File.WriteAllBytesAsync(
    "readonly.pdf", await response.Content.ReadAsByteArrayAsync());
Pedir una contraseña al abrir, con AES-256
cURLbash
curl https://api.pdfblocks.com/v1/add_restrictions \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F owner_password='s3cr3t-owner' \
  -F user_password='open-me-2024' \
  -F encryption_algorithm=AES-256 \
  -o protected.pdf
Pythonpython
import requests

with open('input.pdf', 'rb') as file:
    response = requests.post(
        'https://api.pdfblocks.com/v1/add_restrictions',
        headers={'X-API-Key': 'your_api_key'},
        files={'file': file},
        data={
            'owner_password': 's3cr3t-owner',
            'user_password': 'open-me-2024',
            'encryption_algorithm': 'AES-256',
        },
    )

response.raise_for_status()
with open('protected.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('owner_password', 's3cr3t-owner');
body.set('user_password', 'open-me-2024');
body.set('encryption_algorithm', 'AES-256');

const response = await fetch('https://api.pdfblocks.com/v1/add_restrictions', {
  method: 'POST',
  headers: { 'X-API-Key': 'your_api_key' },
  body,
});

if (!response.ok) throw new Error(`Request failed: ${response.status}`);
await writeFile('protected.pdf', Buffer.from(await response.arrayBuffer()));
PHPphp
<?php
$ch = curl_init('https://api.pdfblocks.com/v1/add_restrictions');
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'),
        'owner_password' => 's3cr3t-owner',
        'user_password' => 'open-me-2024',
        'encryption_algorithm' => 'AES-256',
    ],
]);

$pdf = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200) {
    file_put_contents('protected.pdf', $pdf);
}
Rubyruby
require 'http'

response = HTTP
  .headers('X-API-Key' => 'your_api_key')
  .post('https://api.pdfblocks.com/v1/add_restrictions', form: {
    file: HTTP::FormData::File.new('input.pdf'),
    owner_password: 's3cr3t-owner',
    user_password: 'open-me-2024',
    encryption_algorithm: 'AES-256',
  })

File.write('protected.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("owner_password", "s3cr3t-owner")
	form.WriteField("user_password", "open-me-2024")
	form.WriteField("encryption_algorithm", "AES-256")
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/add_restrictions", &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("protected.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("s3cr3t-owner"), "owner_password" },
    { new StringContent("open-me-2024"), "user_password" },
    { new StringContent("AES-256"), "encryption_algorithm" },
};

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

Acciones relacionadas