# Aggiungere restrizioni a un PDF

Impostare i flag di autorizzazione di un PDF per controllare copia, stampa, modifica e compilazione dei moduli, dietro una password proprietario.

Applicare a un PDF restrizioni di autorizzazione per limitare la copia, la
stampa, la modifica, la compilazione dei moduli e altro ancora, imposte da una
`owner_password`. Le restrizioni sono flag di autorizzazione, da distinguere
dall’[aggiunta di una password](/docs/api/add-password-to-pdf), che imposta la
password richiesta solo per aprire il file; qui è possibile impostare anche una
`user_password` per richiederle entrambe. L’API è *stateless*: il documento
viene elaborato nella regione e non viene mai memorizzato.

## Endpoint

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

Disponibile in tutte le regioni. Vedere [Regioni e residenza dei
dati](/docs/api/regions-and-data-residency) per il routing e la residenza dei
dati.

| Regione             | URL                                                   |
| ------------------- | ----------------------------------------------------- |
| Globale             | `https://api.pdfblocks.com/v1/add_restrictions`       |
| Stati Uniti         | `https://us.api.pdfblocks.com/v1/add_restrictions`    |
| HIPAA Stati Uniti   | `https://hipaa.api.pdfblocks.com/v1/add_restrictions` |
| Unione europea      | `https://eu.api.pdfblocks.com/v1/add_restrictions`    |
| Regno Unito         | `https://uk.api.pdfblocks.com/v1/add_restrictions`    |
| Canada              | `https://ca.api.pdfblocks.com/v1/add_restrictions`    |
| Australia           | `https://au.api.pdfblocks.com/v1/add_restrictions`    |
| Giappone            | `https://jp.api.pdfblocks.com/v1/add_restrictions`    |
| India               | `https://in.api.pdfblocks.com/v1/add_restrictions`    |
| Brasile             | `https://br.api.pdfblocks.com/v1/add_restrictions`    |

## 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](https://dashboard.pdfblocks.com). Vedere
[Autenticazione](/docs/api/authentication) per i dettagli.

## Richiesta

L’endpoint accetta un corpo della richiesta `multipart/form-data`.

<ParamField name="file" type="file" required>
  Il documento PDF di input.
</ParamField>

<ParamField name="owner_password" type="string" required>
  La password proprietario. Da 4 a 32 caratteri ASCII stampabili. Apre il
  documento e ne modifica i [flag di autorizzazione](#flag-di-autorizzazione).
</ParamField>

<ParamField name="user_password" type="string">
  Una password utente facoltativa. Da 4 a 32 caratteri ASCII stampabili. Se
  impostata, il documento non può essere aperto senza di essa. Ometterla, o
  lasciarla vuota, per consentire a chiunque di aprire il documento.
</ParamField>

<ParamField name="encryption_algorithm" type="string" default="AES-128">
  L’algoritmo di crittografia. Uno tra `AES-128` e `AES-256`.
</ParamField>

<ParamField name="allow_copy_content" type="boolean" default="true">
  Consentire la copia di testo e immagini negli appunti.
</ParamField>

<ParamField name="allow_change_content" type="boolean" default="true">
  Consentire la modifica del contenuto del documento.
</ParamField>

<ParamField name="allow_print" type="boolean" default="true">
  Consentire la stampa del documento.
</ParamField>

<ParamField name="allow_print_high_resolution" type="boolean" default="true">
  Consentire la stampa ad alta risoluzione.
</ParamField>

<ParamField name="allow_comment_and_fill_form" type="boolean" default="true">
  Consentire l’aggiunta, la modifica o l’alterazione delle annotazioni e la
  compilazione dei campi modulo.
</ParamField>

<ParamField name="allow_fill_form" type="boolean" default="true">
  Consentire la compilazione dei campi modulo.
</ParamField>

<ParamField name="allow_assemble_document" type="boolean" default="true">
  Consentire l’assemblaggio o la manipolazione del documento (inserire,
  eliminare, ruotare le pagine).
</ParamField>

<ParamField name="allow_accessibility" type="boolean" default="true">
  Consentire ai software di accessibilità di leggere il testo e le immagini del
  documento.
</ParamField>

### Flag di autorizzazione

Ogni flag regola un’azione che il lettore può compiere. Trasmettere il flag come
valore booleano; impostarlo su `false` per disattivare quell’autorizzazione.

| Flag                          | Predefinito | Impostare su `false` per…                                   |
| ----------------------------- | ----------- | ----------------------------------------------------------- |
| `allow_copy_content`          | `true`      | bloccare la copia di testo e immagini negli appunti         |
| `allow_change_content`        | `true`      | bloccare la modifica del contenuto del documento            |
| `allow_print`                 | `true`      | bloccare la stampa del documento                            |
| `allow_print_high_resolution` | `true`      | bloccare la stampa ad alta risoluzione                      |
| `allow_comment_and_fill_form` | `true`      | bloccare l’aggiunta, la modifica o l’alterazione delle annotazioni e la compilazione dei campi modulo |
| `allow_fill_form`             | `true`      | bloccare la compilazione dei campi modulo                   |
| `allow_assemble_document`     | `true`      | bloccare l’assemblaggio o la manipolazione del documento (inserire, eliminare, ruotare le pagine) |
| `allow_accessibility`         | `true`      | impedire ai software di accessibilità di leggere il documento |

<Note>
  Ogni flag vale `true` per impostazione predefinita, quindi non viene
  applicata alcuna restrizione finché non la si richiede. Inviare solo i flag
  che si vogliono disattivare. Le restrizioni sono imposte dalla
  `owner_password`: un lettore che la fornisce può modificare le autorizzazioni.
  Aggiungere una `user_password` solo se si vuole richiedere una password anche
  solo per aprire il file. Per il ciclo di vita completo, vedere [Proteggere i
  documenti](/docs/api/protecting-documents).
</Note>

## Esempi

Bloccare un documento in modo che non possa essere copiato né stampato,
lasciandolo apribile da chiunque:

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

## Risposta

In caso di successo, la risposta è `200 OK` e il corpo contiene il PDF con le
restrizioni applicate:

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

L’output è lo stesso documento con le autorizzazioni richieste applicate. Le
pagine e il contenuto sono invariati. Scrivere il corpo della risposta
direttamente su un file, come fanno gli esempi qui sopra: non viene memorizzato
nulla dalla nostra parte.

## Errori

Le richieste non riuscite restituiscono un corpo `application/problem+json`. Il
più comune per questo endpoint è un `400`, restituito quando un parametro non è
valido, per esempio una `owner_password` che non è composta da 4 a 32 caratteri
ASCII stampabili, con l’oggetto `errors` che nomina ogni 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` mancante o non valida restituisce un `401`. Vedere
[Errori](/docs/api/errors) per tutti i codici di stato e la forma completa della
risposta.

## Ricette

Varianti comuni. Espanderne una per vederla in tutti i linguaggi.

<AccordionGroup>

<Accordion title="Sola lettura: bloccare la copia, la modifica e la stampa">

<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="Richiedere una password per l’apertura, 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>

## Azioni correlate

<CardGroup cols={2}>

<Card title="Rimuovere le restrizioni" href="/docs/api/remove-restrictions-from-pdf">
  Azzerare questi flag di autorizzazione.
</Card>

<Card title="Aggiungere una password" href="/docs/api/add-password-to-pdf">
  Richiedere una password anche solo per aprire il file.
</Card>

<Card title="Rimuovere la password" href="/docs/api/remove-password-from-pdf">
  Decrittografare un PDF protetto da password.
</Card>

<Card title="Rimuovere le firme" href="/docs/api/remove-signatures-from-pdf">
  Rimuovere le firme prima di rielaborare il documento.
</Card>

</CardGroup>
