PDF Blocks
PrezziSupporto
Iniziare gratis
Aprire la pagina

Aggiungere una password a un PDF

Crittografare un PDF in modo che richieda una password per l’apertura, scegliendo l’algoritmo di crittografia.

Crittografare un documento PDF con una password di apertura in modo che non possa essere aperto senza di essa. Questa azione imposta la password richiesta solo per aprire il file, da distinguere dall’aggiunta di restrizioni, che imposta i flag di autorizzazione per azioni come la stampa e la copia. L’algoritmo di crittografia si sceglie in base ai propri requisiti di conformità. L’API è stateless: il documento viene elaborato nella sua regione e non viene mai memorizzato.

Endpoint

POST
/v1/add_password

Disponibile 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_password
Stati Uniti https://us.api.pdfblocks.com/v1/add_password
HIPAA Stati Uniti https://hipaa.api.pdfblocks.com/v1/add_password
Unione europea https://eu.api.pdfblocks.com/v1/add_password
Regno Unito https://uk.api.pdfblocks.com/v1/add_password
Canada https://ca.api.pdfblocks.com/v1/add_password
Australia https://au.api.pdfblocks.com/v1/add_password
Giappone https://jp.api.pdfblocks.com/v1/add_password
India https://in.api.pdfblocks.com/v1/add_password
Brasile https://br.api.pdfblocks.com/v1/add_password

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.

filefilerequired

Il documento PDF di input.

passwordstringrequired

La password richiesta per aprire il documento. Da 4 a 32 caratteri ASCII stampabili (^[\x20-\x7e]{4,32}$).

encryption_algorithmstringdefault:AES-128

L’algoritmo di crittografia. Uno tra AES-128 e AES-256.

Questa azione imposta la password di apertura, che crittografa il documento in modo che non possa essere aperto senza la password. Per limitare ciò che un lettore può fare (stampare, copiare, modificare) senza richiedere una password all’apertura, usare invece Aggiungere restrizioni. Per il ciclo di vita completo, vedere Proteggere i documenti.

Esempi

Crittografare un PDF con AES-256 in modo che non possa essere aperto senza la password:

cURLbash
curl https://api.pdfblocks.com/v1/add_password \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F password='0pen-Sesame' \
  -F encryption_algorithm=AES-256 \
  -o encrypted.pdf
Pythonpython
# pip install requests
import requests

with open('input.pdf', 'rb') as file:
    response = requests.post(
        'https://api.pdfblocks.com/v1/add_password',
        headers={'X-API-Key': 'your_api_key'},
        files={'file': file},
        data={
            'password': '0pen-Sesame',
            'encryption_algorithm': 'AES-256',
        },
    )

response.raise_for_status()
with open('encrypted.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('password', '0pen-Sesame');
body.set('encryption_algorithm', 'AES-256');

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

if (!response.ok) throw new Error(`Request failed: ${response.status}`);
await writeFile('encrypted.pdf', Buffer.from(await response.arrayBuffer()));
PHPphp
<?php
$ch = curl_init('https://api.pdfblocks.com/v1/add_password');
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'),
        'password' => '0pen-Sesame',
        'encryption_algorithm' => 'AES-256',
    ],
]);

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

response = HTTP
  .headers('X-API-Key' => 'your_api_key')
  .post('https://api.pdfblocks.com/v1/add_password', form: {
    file: HTTP::FormData::File.new('input.pdf'),
    password: '0pen-Sesame',
    encryption_algorithm: 'AES-256',
  })

File.write('encrypted.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("password", "0pen-Sesame")
	form.WriteField("encryption_algorithm", "AES-256")
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/add_password", &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("encrypted.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("0pen-Sesame"), "password" },
    { new StringContent("AES-256"), "encryption_algorithm" },
};

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

Risposta

In caso di successo, la risposta è 200 OK e il corpo contiene il PDF crittografato:

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

L’output è lo stesso documento, ora crittografato. Le pagine e il contenuto sono invariati. Scrivere il corpo direttamente in un file, come fanno gli esempi qui sopra: nulla viene memorizzato dalla nostra parte.

Errori

Le richieste non riuscite restituiscono un corpo application/problem+json. L’errore più comune per questo endpoint è un 400, restituito quando un parametro non è valido, per esempio una 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": {
    "password": ["The field 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. Espandere una voce per vederla in tutti i linguaggi.

Crittografare con AES-128, l’algoritmo predefinito
cURLbash
curl https://api.pdfblocks.com/v1/add_password \
  -H 'X-API-Key: your_api_key' \
  -F file=@input.pdf \
  -F password='Tr0ub4dor' \
  -o encrypted.pdf
Pythonpython
import requests

with open('input.pdf', 'rb') as file:
    response = requests.post(
        'https://api.pdfblocks.com/v1/add_password',
        headers={'X-API-Key': 'your_api_key'},
        files={'file': file},
        data={'password': 'Tr0ub4dor'},
    )

response.raise_for_status()
with open('encrypted.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('password', 'Tr0ub4dor');

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

if (!response.ok) throw new Error(`Request failed: ${response.status}`);
await writeFile('encrypted.pdf', Buffer.from(await response.arrayBuffer()));
PHPphp
<?php
$ch = curl_init('https://api.pdfblocks.com/v1/add_password');
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'),
        'password' => 'Tr0ub4dor',
    ],
]);

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

response = HTTP
  .headers('X-API-Key' => 'your_api_key')
  .post('https://api.pdfblocks.com/v1/add_password', form: {
    file: HTTP::FormData::File.new('input.pdf'),
    password: 'Tr0ub4dor',
  })

File.write('encrypted.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("password", "Tr0ub4dor")
	form.Close()

	req, _ := http.NewRequest("POST", "https://api.pdfblocks.com/v1/add_password", &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("encrypted.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("Tr0ub4dor"), "password" },
};

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

Azioni correlate