# 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](/docs/api/add-password-to-pdf), 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

<Endpoint method="POST" path="/v1/add_restrictions" />

Disponible en todas las regiones. Consulte [Regiones y residencia de
datos](/docs/api/regions-and-data-residency) 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](https://dashboard.pdfblocks.com). Consulte
[Autenticación](/docs/api/authentication) para más detalles.

## Solicitud

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

<ParamField name="file" type="file" required>
  El documento PDF de entrada.
</ParamField>

<ParamField name="owner_password" type="string" required>
  La contraseña de propietario. De 4 a 32 caracteres ASCII imprimibles. Abre
  el documento y cambia sus [indicadores de permiso](#indicadores-de-permiso).
</ParamField>

<ParamField name="user_password" type="string">
  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.
</ParamField>

<ParamField name="encryption_algorithm" type="string" default="AES-128">
  El algoritmo de cifrado. Uno de `AES-128` o `AES-256`.
</ParamField>

<ParamField name="allow_copy_content" type="boolean" default="true">
  Permitir copiar texto e imágenes al portapapeles.
</ParamField>

<ParamField name="allow_change_content" type="boolean" default="true">
  Permitir cambiar el contenido del documento.
</ParamField>

<ParamField name="allow_print" type="boolean" default="true">
  Permitir imprimir el documento.
</ParamField>

<ParamField name="allow_print_high_resolution" type="boolean" default="true">
  Permitir imprimir en alta resolución.
</ParamField>

<ParamField name="allow_comment_and_fill_form" type="boolean" default="true">
  Permitir añadir, editar o modificar anotaciones y rellenar campos de
  formulario.
</ParamField>

<ParamField name="allow_fill_form" type="boolean" default="true">
  Permitir rellenar campos de formulario.
</ParamField>

<ParamField name="allow_assemble_document" type="boolean" default="true">
  Permitir ensamblar o manipular el documento (insertar, eliminar y girar
  páginas).
</ParamField>

<ParamField name="allow_accessibility" type="boolean" default="true">
  Permitir que el software de accesibilidad lea el texto y las imágenes del
  documento.
</ParamField>

### 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                                  |

<Note>
  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](/docs/api/protecting-documents).
</Note>

## Ejemplos

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

<CodeGroup>

```bash title="cURL"
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
```

```python title="Python"
# 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)
```

```javascript title="Node.js"
// 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()));
```

```php title="PHP"
<?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);
}
```

```ruby title="Ruby"
# 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?
```

```go title="Go"
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)
}
```

```csharp title="C#"
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());
```

</CodeGroup>

## Respuesta

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

```http
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:

```json
{
  "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](/docs/api/errors) 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.

<AccordionGroup>

<Accordion title="Solo lectura: bloquear la copia, la edición y la impresión">

<CodeGroup>

```bash title="cURL"
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
```

```python title="Python"
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)
```

```javascript title="Node.js"
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()));
```

```php title="PHP"
<?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);
}
```

```ruby title="Ruby"
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?
```

```go title="Go"
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)
}
```

```csharp title="C#"
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());
```

</CodeGroup>

</Accordion>

<Accordion title="Pedir una contraseña al abrir, con AES-256">

<CodeGroup>

```bash title="cURL"
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
```

```python title="Python"
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)
```

```javascript title="Node.js"
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()));
```

```php title="PHP"
<?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);
}
```

```ruby title="Ruby"
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?
```

```go title="Go"
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)
}
```

```csharp title="C#"
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());
```

</CodeGroup>

</Accordion>

</AccordionGroup>

## Acciones relacionadas

<CardGroup cols={2}>

<Card title="Quitar restricciones" href="/docs/api/remove-restrictions-from-pdf">
  Borre estos indicadores de permiso.
</Card>

<Card title="Añadir una contraseña" href="/docs/api/add-password-to-pdf">
  Pida una contraseña solo para abrir el archivo.
</Card>

<Card title="Quitar la contraseña" href="/docs/api/remove-password-from-pdf">
  Descifre un PDF protegido con contraseña.
</Card>

<Card title="Quitar firmas" href="/docs/api/remove-signatures-from-pdf">
  Quite las firmas antes de volver a procesar.
</Card>

</CardGroup>
