Protecting PDFs with a password | laravel-pdf-rust | Spatie       

 SPATIE  

laravel-pdf-rust
================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-pdf-rust](https://spatie.be/docs/laravel-pdf-rust/v1)  Basic-usage  Protecting PDFs with a password

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/laravel-pdf-rust/v1) 

  Protecting PDFs with a password    
- [ Introduction ](https://spatie.be/docs/laravel-pdf-rust/v1/introduction)
- [ Support us ](https://spatie.be/docs/laravel-pdf-rust/v1/support-us)
- [ Requirements ](https://spatie.be/docs/laravel-pdf-rust/v1/requirements)
- [ Installation &amp; setup ](https://spatie.be/docs/laravel-pdf-rust/v1/installation-setup)
- [ Questions and issues ](https://spatie.be/docs/laravel-pdf-rust/v1/questions-issues)
- [ Changelog ](https://spatie.be/docs/laravel-pdf-rust/v1/changelog)
- [ Testing ](https://spatie.be/docs/laravel-pdf-rust/v1/testing)
- [ About us ](https://spatie.be/docs/laravel-pdf-rust/v1/about-us)

Basic usage
-----------

- [ Creating PDFs ](https://spatie.be/docs/laravel-pdf-rust/v1/basic-usage/creating-pdfs)
- [ Responding with PDFs ](https://spatie.be/docs/laravel-pdf-rust/v1/basic-usage/responding-with-pdfs)
- [ Formatting PDFs ](https://spatie.be/docs/laravel-pdf-rust/v1/basic-usage/formatting-pdfs)
- [ Saving PDFs to disks ](https://spatie.be/docs/laravel-pdf-rust/v1/basic-usage/saving-pdfs-to-disks)
- [ Attaching PDFs to mails ](https://spatie.be/docs/laravel-pdf-rust/v1/basic-usage/attaching-pdfs-to-mails)
- [ Queued PDF generation ](https://spatie.be/docs/laravel-pdf-rust/v1/basic-usage/queued-pdf-generation)
- [ Testing PDFs ](https://spatie.be/docs/laravel-pdf-rust/v1/basic-usage/testing-pdfs)
- [ Setting defaults ](https://spatie.be/docs/laravel-pdf-rust/v1/basic-usage/setting-defaults)
- [ Protecting PDFs with a password ](https://spatie.be/docs/laravel-pdf-rust/v1/basic-usage/protecting-pdfs-with-a-password)

Drivers
-------

- [ Configuration ](https://spatie.be/docs/laravel-pdf-rust/v1/drivers/configuration)
- [ Customizing Browsershot ](https://spatie.be/docs/laravel-pdf-rust/v1/drivers/customizing-browsershot)
- [ Using the Cloudflare driver ](https://spatie.be/docs/laravel-pdf-rust/v1/drivers/using-the-cloudflare-driver)
- [ Using the DOMPDF driver ](https://spatie.be/docs/laravel-pdf-rust/v1/drivers/using-the-dompdf-driver)
- [ Generating PDFs on AWS Lambda ](https://spatie.be/docs/laravel-pdf-rust/v1/drivers/generating-pdfs-on-aws-lambda)
- [ Using the Chrome driver ](https://spatie.be/docs/laravel-pdf-rust/v1/drivers/using-the-chrome-driver)
- [ Using the Gotenberg driver ](https://spatie.be/docs/laravel-pdf-rust/v1/drivers/using-the-gotenberg-driver)
- [ Using the WeasyPrint driver ](https://spatie.be/docs/laravel-pdf-rust/v1/drivers/using-the-weasyprint-driver)
- [ Custom drivers ](https://spatie.be/docs/laravel-pdf-rust/v1/drivers/custom-drivers)

Advanced usage
--------------

- [ Creating PDFs with multiple pages ](https://spatie.be/docs/laravel-pdf-rust/v1/advanced-usage/creating-pdfs-with-multiple-pages)
- [ Using Tailwind ](https://spatie.be/docs/laravel-pdf-rust/v1/advanced-usage/using-tailwind)
- [ Extending with Macros ](https://spatie.be/docs/laravel-pdf-rust/v1/advanced-usage/extending-with-macros)
- [ Waiting for readiness ](https://spatie.be/docs/laravel-pdf-rust/v1/advanced-usage/waiting-for-readiness)
- [ Caching PDFs ](https://spatie.be/docs/laravel-pdf-rust/v1/advanced-usage/caching-pdfs)

 Protecting PDFs with a password
===============================

###  On this page 

1. [ Owner password and permissions ](#content-owner-password-and-permissions)
2. [ Supported drivers ](#content-supported-drivers)
3. [ Decrypting a PDF ](#content-decrypting-a-pdf)
4. [ Using a custom encrypter ](#content-using-a-custom-encrypter)

You can password-protect a generated PDF with the `encrypt` method. The PDF is encrypted with AES-256 in Rust after it is rendered, so no external binaries (such as `qpdf`) are required. No additional encryption package is needed.

Pass a user password to require it before the document can be opened.

```
use serde_json::json;
use spatie_pdf::PdfEncryption;

pdf.view("pdf.invoice", json!({"invoice": invoice}))
    .encrypt(PdfEncryption {
        user_password: "open-sesame".into(),
        owner_password: None,
        permissions: None,
    })
    .save("/some/directory/invoice.pdf").await?;
```

Owner password and permissions
--------------------------------------------------------------------------------------------------------------------------------------------------

You can also set an owner password and restrict what readers may do with the document. The owner password grants full access (including changing the permissions), while the user password opens the document with the restrictions applied.

Permissions are passed as a list of `Permission` cases. Only the permissions you pass are granted. When you pass `None`, every permission is granted and the password only controls opening the document. An empty list grants none.

```
use serde_json::json;
use spatie_pdf::{PdfEncryption, Permission};

pdf.view("pdf.invoice", json!({"invoice": invoice}))
    .encrypt(PdfEncryption {
        user_password: "open-sesame".into(),
        owner_password: Some("owner-secret".into()),
        permissions: Some(vec![Permission::Print, Permission::Copy]),
    })
    .save("/some/directory/invoice.pdf").await?;
```

The available permissions are `Print`, `Copy`, `Modify`, `Annotate`, `FillForms`, `Extract`, `Assemble`, and `PrintHighResolution`.

Links, the document tag tree, and metadata set with `meta` are preserved. Permissions are advisory; PDF readers decide whether to enforce them. If no owner password is supplied, the encrypter generates a random one.

> When you generate a protected PDF on the queue with `save_queued`, the passwords are stored in the queue payload until the job runs. Make sure your queue storage (database, Redis) is secured accordingly. Debug output omits the passwords, but serialization intentionally does not.

Supported drivers
-----------------------------------------------------------------------------------------------------------

Encryption is applied as a post-processing step, so it works with any driver that produces a PDF supported by `lopdf`, including compressed object streams.

Decrypting a PDF
--------------------------------------------------------------------------------------------------------

You can decrypt a protected PDF with `decrypt_file` or `decrypt`. They accept a path to a PDF file or the raw PDF contents respectively, together with the user or owner password, and return the decrypted PDF.

```
use spatie_pdf::{decrypt, decrypt_file};

// Pass a path...
let decrypted = decrypt_file(&path, "open-sesame")?;

// ...or the raw contents
let decrypted = decrypt(&contents, "open-sesame")?;
```

When the password is incorrect, an error is returned, so you can handle a wrong password.

```
use spatie_pdf::decrypt_file;

match decrypt_file(&path, password) {
    Ok(decrypted) => {
        // Use the decrypted PDF.
    }
    Err(error) => {
        // The password was incorrect, or the PDF could not be decrypted.
    }
}
```

Using a custom encrypter
--------------------------------------------------------------------------------------------------------------------------------

The default encrypter handles AES-256 protection. If you want to use a different strategy (for example a `qpdf` binary or a commercial library), implement the `PdfEncrypter` contract and pass it to the default builder.

```
pdf.defaults(pdf.builder().encrypter(MyEncrypter));
```

Here is the contract implementation. This version delegates to the default; replace its method bodies with your encryption strategy.

```
use spatie_pdf::{DefaultPdfEncrypter, PdfEncrypter, PdfEncryption, Result};

struct MyEncrypter;

impl PdfEncrypter for MyEncrypter {
    fn encrypt(&self, pdf: &[u8], encryption: &PdfEncryption) -> Result<Vec<u8>> {
        DefaultPdfEncrypter.encrypt(pdf, encryption)
    }

    fn decrypt(&self, pdf: &[u8], password: &str) -> Result<Vec<u8>> {
        DefaultPdfEncrypter.decrypt(pdf, password)
    }

    fn cache_identity(&self) -> String {
        "my-encrypter-v1".into()
    }
}
```

Supply the same encrypter to the queue worker. Its `cache_identity` must change when its configuration changes the output.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
