Añadir una contraseña a un PDF
Cifre un PDF para que pida una contraseña al abrirse, eligiendo el algoritmo de cifrado.
Cifre un documento PDF con una contraseña de apertura para que no pueda abrirse sin ella. Esto establece la contraseña necesaria solo para abrir el archivo, algo distinto de añadir restricciones, que establece indicadores de permiso para acciones como imprimir y copiar. Elija el algoritmo de cifrado que corresponda a sus necesidades de cumplimiento. La API es stateless: su documento se procesa en la región y nunca se almacena.
Endpoint
/v1/add_passwordDisponible 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_password |
| Estados Unidos | https://us.api.pdfblocks.com/v1/add_password |
| HIPAA de EE. UU. | https://hipaa.api.pdfblocks.com/v1/add_password |
| Unión Europea | https://eu.api.pdfblocks.com/v1/add_password |
| Reino Unido | https://uk.api.pdfblocks.com/v1/add_password |
| Canadá | https://ca.api.pdfblocks.com/v1/add_password |
| Australia | https://au.api.pdfblocks.com/v1/add_password |
| Japón | https://jp.api.pdfblocks.com/v1/add_password |
| India | https://in.api.pdfblocks.com/v1/add_password |
| Brasil | https://br.api.pdfblocks.com/v1/add_password |
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.
filefilerequiredEl documento PDF de entrada.
passwordstringrequiredLa contraseña necesaria para abrir el documento. De 4 a 32 caracteres ASCII
imprimibles (^[\x20-\x7e]{4,32}$).
encryption_algorithmstringdefault:AES-128El algoritmo de cifrado. Uno de AES-128 o AES-256.
Esto establece la contraseña de apertura, que cifra el documento para que no pueda abrirse sin ella. Para limitar lo que puede hacer un lector (imprimir, copiar, editar) sin pedir una contraseña al abrir, use Añadir restricciones en su lugar. Para ver el ciclo completo, consulte Proteger documentos.
Ejemplos
Cifre un PDF con AES-256 para que no pueda abrirse sin la contraseña:
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# 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.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()));<?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);
}# 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?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)
}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());Respuesta
Si todo va bien, la respuesta es 200 OK con el PDF cifrado como cuerpo:
HTTP/1.1 200 OK
Content-Type: application/pdf
Content-Length: 48213La salida es el mismo documento, ahora cifrado: 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 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": {
"password": ["The field 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.
Cifrar con el AES-128 predeterminado
curl https://api.pdfblocks.com/v1/add_password \
-H 'X-API-Key: your_api_key' \
-F file=@input.pdf \
-F password='Tr0ub4dor' \
-o encrypted.pdfimport 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)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()));<?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);
}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?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)
}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());