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, 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
/v1/add_restrictionsDisponibile in tutte le regioni. Vedere Regioni e residenza dei dati 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. Vedere
Autenticazione per i dettagli.
Richiesta
L’endpoint accetta un corpo della richiesta multipart/form-data.
filefilerequiredIl documento PDF di input.
owner_passwordstringrequiredLa password proprietario. Da 4 a 32 caratteri ASCII stampabili. Apre il documento e ne modifica i flag di autorizzazione.
user_passwordstringUna 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.
encryption_algorithmstringdefault:AES-128L’algoritmo di crittografia. Uno tra AES-128 e AES-256.
allow_copy_contentbooleandefault:trueConsentire la copia di testo e immagini negli appunti.
allow_change_contentbooleandefault:trueConsentire la modifica del contenuto del documento.
allow_printbooleandefault:trueConsentire la stampa del documento.
allow_print_high_resolutionbooleandefault:trueConsentire la stampa ad alta risoluzione.
allow_comment_and_fill_formbooleandefault:trueConsentire l’aggiunta, la modifica o l’alterazione delle annotazioni e la compilazione dei campi modulo.
allow_fill_formbooleandefault:trueConsentire la compilazione dei campi modulo.
allow_assemble_documentbooleandefault:trueConsentire l’assemblaggio o la manipolazione del documento (inserire, eliminare, ruotare le pagine).
allow_accessibilitybooleandefault:trueConsentire ai software di accessibilità di leggere il testo e le immagini del documento.
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 |
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.
Esempi
Bloccare un documento in modo che non possa essere copiato né stampato, lasciandolo apribile da chiunque:
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# 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.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
$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);
}# 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?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)
}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());Risposta
In caso di successo, la risposta è 200 OK e il corpo contiene il PDF con le
restrizioni applicate:
HTTP/1.1 200 OK
Content-Type: application/pdf
Content-Length: 48213L’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:
{
"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 per tutti i codici di stato e la forma completa della
risposta.
Ricette
Varianti comuni. Espanderne una per vederla in tutti i linguaggi.
Sola lettura: bloccare la copia, la modifica e la stampa
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.pdfimport 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)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
$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);
}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?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)
}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());Richiedere una password per l’apertura, con AES-256
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.pdfimport 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)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
$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);
}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?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)
}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());