PDF Blocks
PreçosSuporte
Começar grátis
Abrir a página

Adicionar restrições a um PDF

Defina os sinalizadores de permissão de um PDF, controlando a cópia, a impressão, a edição e o preenchimento de formulários, por trás de uma senha de proprietário.

Aplique restrições de permissão a um PDF para limitar a cópia, a impressão, a edição, o preenchimento de formulários e mais, tudo isso imposto por uma owner_password. As restrições são sinalizadores de permissão, diferentes de adicionar uma senha, que define a senha exigida apenas para abrir o arquivo; você também pode definir aqui uma user_password para exigir as duas. A API é stateless: seu documento é processado na região e nunca é armazenado.

Endpoint

POST
/v1/add_restrictions

Disponível em todas as regiões. Consulte Regiões e residência de dados para o roteamento e a residência de dados.

Região URL
Global https://api.pdfblocks.com/v1/add_restrictions
Estados Unidos https://us.api.pdfblocks.com/v1/add_restrictions
HIPAA Estados Unidos https://hipaa.api.pdfblocks.com/v1/add_restrictions
União Europeia https://eu.api.pdfblocks.com/v1/add_restrictions
Reino Unido https://uk.api.pdfblocks.com/v1/add_restrictions
Canadá https://ca.api.pdfblocks.com/v1/add_restrictions
Austrália https://au.api.pdfblocks.com/v1/add_restrictions
Japão https://jp.api.pdfblocks.com/v1/add_restrictions
Índia https://in.api.pdfblocks.com/v1/add_restrictions
Brasil https://br.api.pdfblocks.com/v1/add_restrictions

Autenticação

Autentique cada requisição com sua chave de API secreta no cabeçalho X-API-Key, por HTTPS. Crie e gerencie suas chaves no dashboard. Consulte Autenticação para mais detalhes.

Requisição

O endpoint aceita um corpo de requisição multipart/form-data.

filefilerequired

O documento PDF de entrada.

owner_passwordstringrequired

A senha de proprietário. De 4 a 32 caracteres ASCII imprimíveis. Abre o documento e altera seus sinalizadores de permissão.

user_passwordstring

Uma senha de usuário opcional. De 4 a 32 caracteres ASCII imprimíveis. Quando definida, o documento não pode ser aberto sem ela. Omita-a, ou deixe-a vazia, para que qualquer pessoa possa abrir o documento.

encryption_algorithmstringdefault:AES-128

O algoritmo de criptografia: AES-128 ou AES-256.

allow_copy_contentbooleandefault:true

Permitir copiar texto e imagens para a área de transferência.

allow_change_contentbooleandefault:true

Permitir alterar o conteúdo do documento.

allow_printbooleandefault:true

Permitir imprimir o documento.

allow_print_high_resolutionbooleandefault:true

Permitir imprimir em alta resolução.

allow_comment_and_fill_formbooleandefault:true

Permitir adicionar, editar ou modificar anotações e preencher campos de formulário.

allow_fill_formbooleandefault:true

Permitir preencher campos de formulário.

allow_assemble_documentbooleandefault:true

Permitir montar ou manipular o documento (inserir, excluir e girar páginas).

allow_accessibilitybooleandefault:true

Permitir que softwares de acessibilidade leiam o texto e as imagens do documento.

Sinalizadores de permissão

Cada sinalizador rege uma ação que o leitor pode executar. Envie o sinalizador como um booleano; defina-o como false para desativar essa permissão.

Sinalizador Padrão Defina como false para…
allow_copy_content true bloquear a cópia de texto e imagens para a área de transferência
allow_change_content true bloquear a alteração do conteúdo do documento
allow_print true bloquear a impressão do documento
allow_print_high_resolution true bloquear a impressão em alta resolução
allow_comment_and_fill_form true bloquear a adição, a edição ou a modificação de anotações e o preenchimento de campos de formulário
allow_fill_form true bloquear o preenchimento de campos de formulário
allow_assemble_document true bloquear a montagem ou a manipulação do documento (inserir, excluir e girar páginas)
allow_accessibility true impedir que softwares de acessibilidade leiam o documento

Todo sinalizador vale true por padrão, então nada fica restrito a menos que você peça. Envie apenas os sinalizadores que quiser desativar. As restrições são impostas pela owner_password: um leitor que a forneça pode alterar as permissões. Adicione uma user_password apenas se você também quiser exigir uma senha só para abrir o arquivo. Para o ciclo de vida completo, consulte Proteger documentos.

Exemplos

Bloqueie um documento para que ele não possa ser copiado nem impresso, mas ainda possa ser aberto por qualquer pessoa:

cURLbash
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
Pythonpython
# 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.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('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()));
PHPphp
<?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);
}
Rubyruby
# 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?
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("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)
}
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("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());

Resposta

Em caso de sucesso, a resposta é 200 OK com o PDF restrito no corpo:

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

A saída é o mesmo documento com as permissões solicitadas aplicadas. Suas páginas e seu conteúdo não mudam. Grave o corpo diretamente em um arquivo, como fazem os exemplos acima; nada é armazenado do nosso lado.

Erros

Requisições com falha retornam um corpo application/problem+json. O erro mais comum neste endpoint é um 400, retornado quando um parâmetro é inválido (por exemplo, uma owner_password que não tem de 4 a 32 caracteres ASCII imprimíveis), com o objeto errors nomeando cada 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}$'."]
  }
}

Uma X-API-Key ausente ou inválida retorna um 401. Consulte Erros para ver todos os códigos de status e o formato completo da resposta.

Receitas

Variações comuns. Expanda uma para vê-la em todas as linguagens.

Somente leitura: bloquear a cópia, a edição e a impressão
cURLbash
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
Pythonpython
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)
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('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()));
PHPphp
<?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);
}
Rubyruby
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?
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("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)
}
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("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());
Exigir uma senha para abrir, com AES-256
cURLbash
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
Pythonpython
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)
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('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()));
PHPphp
<?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);
}
Rubyruby
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?
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("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)
}
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("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());

Ações relacionadas