PDF Blocks
PreiseSupport
Kostenlos starten
Seite öffnen

Ein Passwort zu einem PDF hinzufügen

Verschlüsseln Sie ein PDF so, dass es zum Öffnen ein Passwort verlangt, und wählen Sie dabei den Verschlüsselungsalgorithmus.

Verschlüsseln Sie ein PDF-Dokument mit einem Passwort zum Öffnen, damit es ohne dieses nicht geöffnet werden kann. Damit wird nur das Passwort festgelegt, das zum Öffnen der Datei nötig ist, im Unterschied zum Hinzufügen von Einschränkungen, das Berechtigungs-Flags für Aktionen wie Drucken und Kopieren setzt. Wählen Sie den Verschlüsselungsalgorithmus passend zu Ihren Compliance-Anforderungen. Die API ist stateless: Ihr Dokument wird in der Region verarbeitet und niemals gespeichert.

Endpoint

POST
/v1/add_password

In allen Regionen verfügbar. Hinweise zu Routing und Datenresidenz finden Sie unter Regionen und Datenresidenz.

Region URL
Global https://api.pdfblocks.com/v1/add_password
USA https://us.api.pdfblocks.com/v1/add_password
HIPAA USA https://hipaa.api.pdfblocks.com/v1/add_password
Europäische Union https://eu.api.pdfblocks.com/v1/add_password
Vereinigtes Königreich https://uk.api.pdfblocks.com/v1/add_password
Kanada https://ca.api.pdfblocks.com/v1/add_password
Australien https://au.api.pdfblocks.com/v1/add_password
Japan https://jp.api.pdfblocks.com/v1/add_password
Indien https://in.api.pdfblocks.com/v1/add_password
Brasilien https://br.api.pdfblocks.com/v1/add_password

Authentifizierung

Authentifizieren Sie jede Anfrage mit Ihrem geheimen API-Schlüssel im Header X-API-Key, über HTTPS. Schlüssel erstellen und verwalten Sie im Dashboard. Einzelheiten finden Sie unter Authentifizierung.

Anfrage

Der Endpoint nimmt einen Anfragetext vom Typ multipart/form-data entgegen.

filefilerequired

Das PDF-Eingabedokument.

passwordstringrequired

Das Passwort, das zum Öffnen des Dokuments nötig ist. 4 bis 32 druckbare ASCII-Zeichen (^[\x20-\x7e]{4,32}$).

encryption_algorithmstringdefault:AES-128

Der Verschlüsselungsalgorithmus. Entweder AES-128 oder AES-256.

Dies legt das Passwort zum Öffnen fest: Es verschlüsselt das Dokument, sodass es ohne dieses Passwort nicht geöffnet werden kann. Um zu begrenzen, was ein Leser tun kann (Drucken, Kopieren, Bearbeiten), ohne ein Passwort zum Öffnen zu verlangen, verwenden Sie stattdessen Einschränkungen hinzufügen. Zum vollständigen Lebenszyklus siehe Dokumente schützen.

Beispiele

Verschlüsseln Sie ein PDF mit AES-256, sodass es ohne das Passwort nicht geöffnet werden kann:

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());

Antwort

Bei Erfolg lautet die Antwort 200 OK und enthält das verschlüsselte PDF als Antworttext:

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

Die Ausgabe ist dasselbe Dokument, nun verschlüsselt. Seine Seiten und sein Inhalt sind unverändert. Schreiben Sie den Antworttext direkt in eine Datei, wie die Beispiele oben es tun; bei uns wird nichts gespeichert.

Fehler

Fehlgeschlagene Anfragen liefern einen Antworttext vom Typ application/problem+json. Am häufigsten ist bei diesem Endpoint der Status 400, der zurückgegeben wird, wenn ein Parameter ungültig ist (zum Beispiel ein password, das nicht aus 4 bis 32 druckbaren ASCII-Zeichen besteht); dabei nennt das Objekt errors jedes betroffene Feld:

{
  "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}$'."]
  }
}

Ein fehlender oder ungültiger X-API-Key gibt einen 401 zurück. Alle Statuscodes und die vollständige Form der Antwort finden Sie unter Fehler.

Rezepte

Häufige Varianten. Klappen Sie eine auf, um sie in allen Sprachen zu sehen.

Mit dem Standard AES-128 verschlüsseln
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());

Verwandte Aktionen