Formatting PDFs | 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  Formatting PDFs

 Version   v1      

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

  Formatting PDFs    
- [ 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)

 Formatting PDFs
===============

###  On this page 

1. [ Setting a header and footer ](#content-setting-a-header-and-footer)
2. [ Page orientation ](#content-page-orientation)
3. [ Paper format ](#content-paper-format)
4. [ Paper size ](#content-paper-size)
5. [ Page margins ](#content-page-margins)
6. [ Scale ](#content-scale)
7. [ Page ranges ](#content-page-ranges)
8. [ Tagged PDF ](#content-tagged-pdf)
9. [ Document outline ](#content-document-outline)
10. [ PDF metadata ](#content-pdf-metadata)
11. [ Conditional formatting ](#content-conditional-formatting)
12. [ Debugging ](#content-debugging)
13. [ Background color ](#content-background-color)

There are various options to customize the output of the PDFs. You can change the page size, the orientation, the margins, and much more!

Setting a header and footer
-----------------------------------------------------------------------------------------------------------------------------------------

You can set a header and footer on every page of the PDF. You can use the `header_view` and `footer_view` methods to set the HTML for the header and footer.

```
use serde_json::json;

pdf.view("pdf.invoice", json!({"invoice": invoice}))
    .header_view("pdf.invoice.header", json!({}))
    .footer_view("pdf.invoice.footer", json!({}))
    .save("/some/directory/invoice-april-2022.pdf").await?;
```

You can also use the `header_html` and `footer_html` methods to set the HTML for the header and footer.

```
use serde_json::json;

pdf.view("pdf.invoice", json!({"invoice": invoice}))
    .header_html("<div>My header</div>")
    .footer_html("<div>My footer</div>")
    .save("/some/directory/invoice-april-2022.pdf").await?;
```

The header and footer do not use the CSS set in the main view. In your header and footer HTML, you should add any CSS you need. Here's an example footer view:

```
<style>
footer {
    font-size: 12px;
}
</style>

<footer>
  This is the footer
</footer>
```

Inside the footer, you can use the following HTML constants:

- `PAGE_NUMBER`: The current page number
- `TOTAL_PAGES`: The total number of pages

These counters work with Browsershot, Cloudflare, Chrome, Gotenberg and WeasyPrint. The DOMPDF driver does not support these counters. Your template engine can insert the constants; the package does not parse Blade directives.

### Display Images in Headers and Footers

You can add an image using `inlined_image`. Load the image through your application's authorized file or HTTP adapter, then pass its bytes and MIME type. The helper does not read paths or fetch URLs implicitly.

```
use spatie_pdf::inlined_image;

let logo = std::fs::read(public_path.join("assets/logo.png"))?;
let image = inlined_image(&logo, "image/png")?;
```

### Header and footer caveats

Headers and footers are rendered by Chromium in a separate, isolated document. This applies to the Chrome, Browsershot, Gotenberg, and Cloudflare drivers, and it has a few consequences worth knowing about.

**Set a font size explicitly.** The isolated document uses a tiny default font size (roughly 1px), so text will be nearly invisible unless you set your own. Always define a `font-size` in your header and footer CSS.

```
<style>
    html {
        font-size: 16px;
    }
</style>
```

**The header and footer span the full page width.** The left and right page margins you set with `margins()` apply to the main content, not to the header and footer. To line them up with your content, add matching horizontal padding yourself. If your left and right margins are `0.39in`, use:

```
<style>
    body {
        margin: 0;
        padding: 0 0.39in;
    }
</style>
```

**Avoid `width: 100%`.** Because the header and footer already span the full paper width, `width: 100%` overflows the page even with `box-sizing: border-box`. Rely on the body padding above instead of setting an explicit width, or subtract your horizontal margins from the width:

```
.header {
    width: calc(100% - 0.78in); /* left margin plus right margin */
}
```

**Make room for the header and footer with your top and bottom margins.** Chromium draws the header inside the top margin and the footer inside the bottom margin. It does not enlarge those margins to fit their content, so if a margin is smaller than the rendered header or footer, it will overlap your main content. Increase the top and bottom margins until there is enough room.

```
use spatie_pdf::Unit;

pdf.view("pdf.invoice", data.clone())
    .margins(0.9, 0.39, 0.6, 0.39, Unit::Inch)
    .header_view("pdf.header", data.clone())
    .footer_view("pdf.footer", data)
    .save("/some/directory/invoice.pdf").await?;
```

Page orientation
--------------------------------------------------------------------------------------------------------

By default, all PDFs are created in portrait mode. You can change this by calling the `landscape` method.

```
use serde_json::json;

pdf.view("pdf.invoice", json!({"invoice": invoice}))
    .landscape()
    .save("/some/directory/invoice-april-2022.pdf").await?;
```

Alternatively, you can use the `orientation` method.

```
use serde_json::json;
use spatie_pdf::Orientation;

pdf.view("pdf.invoice", json!({"invoice": invoice}))
    .orientation(Orientation::Landscape)
    .save("/some/directory/invoice-april-2022.pdf").await?;
```

Paper format
--------------------------------------------------------------------------------------------

By default, Chromium PDFs are created in Letter format. You can change this by calling the `format` method. DOMPDF retains its A4 default; WeasyPrint is normalized to Letter by this adapter.

```
use serde_json::json;
use spatie_pdf::Format;

pdf.view("pdf.invoice", json!({"invoice": invoice}))
    .format(Format::A3)
    .save("/some/directory/invoice-april-2022.pdf").await?;
```

These are the available formats of the `Format` enum:

```
Letter: 8.5in  x  11in
Legal: 8.5in  x  14in
Tabloid: 11in  x  17in
Ledger: 17in  x  11in
A0: 33.1in  x  46.8in
A1: 23.4in  x  33.1in
A2: 16.54in  x  23.4in
A3: 11.7in  x  16.54in
A4: 8.27in  x  11.7in
A5: 5.83in  x  8.27in
A6: 4.13in  x  5.83in
```

Paper size
--------------------------------------------------------------------------------------

If you don't want to use standardized formats, you can also use the `paper_size` method instead.

```
use serde_json::json;
use spatie_pdf::Unit;

pdf.view("pdf.receipt", json!({"order": order}))
    .paper_size(57.0, 500.0, Unit::Millimeter)
    .save("/some/directory/receipt-12345.pdf").await?;
```

Page margins
--------------------------------------------------------------------------------------------

Margins can be set using the `margins` method. Rust requires an explicit unit.

```
use serde_json::json;
use spatie_pdf::Unit;

pdf.view("pdf.invoice", json!({"invoice": invoice}))
    .margins(top, right, bottom, left, Unit::Millimeter)
    .save("/some/directory/invoice-april-2022.pdf").await?;
```

You can give a custom unit to `margins` as the fifth parameter.

```
use serde_json::json;
use spatie_pdf::Unit;

pdf.view("pdf.invoice", json!({"invoice": invoice}))
    .margins(top, right, bottom, left, Unit::Pixel)
    .save("/some/directory/invoice-april-2022.pdf").await?;
```

Scale
-----------------------------------------------------------------------

You can scale the content of the PDF using the `scale` method. The value must be between 0.1 and 2.0.

```
use serde_json::json;

pdf.view("pdf.invoice", json!({"invoice": invoice}))
    .scale(0.75)
    .save("/some/directory/invoice.pdf").await?;
```

Scale is supported by Browsershot, Cloudflare, Chrome and Gotenberg. DOMPDF and WeasyPrint reject this option.

Page ranges
-----------------------------------------------------------------------------------------

You can select specific pages to include in the output using the `page_ranges` method. The format supports individual pages and ranges.

```
use serde_json::json;

pdf.view("pdf.report", json!({"report": report}))
    .page_ranges("1-3, 5")
    .save("/some/directory/report.pdf").await?;
```

Page ranges are supported by Browsershot, Cloudflare, Chrome and Gotenberg. DOMPDF and WeasyPrint reject this option.

Tagged PDF
--------------------------------------------------------------------------------------

You can generate a tagged (accessible) PDF using the `tagged` method. Tagged PDFs include structural information that makes them accessible to screen readers.

```
use serde_json::json;

pdf.view("pdf.invoice", json!({"invoice": invoice}))
    .tagged()
    .save("/some/directory/invoice.pdf").await?;
```

Support depends on the driver and engine version. DOMPDF rejects this option.

Document outline
--------------------------------------------------------------------------------------------------------

You can generate a document outline (bookmarks) using the `document_outline` method. The outline is built from the headings in your view, and lets readers jump to a section from the sidebar of their PDF viewer.

```
use serde_json::json;

pdf.view("pdf.report", json!({"report": report}))
    .document_outline()
    .save("/some/directory/report.pdf").await?;
```

Native Chrome forwards the DevTools outline flag; WeasyPrint creates bookmarks from headings by default. DOMPDF rejects this option.

PDF metadata
--------------------------------------------------------------------------------------------

You can set PDF document metadata such as title, author, subject, and keywords using the `meta` method. This metadata is displayed in PDF viewers, for example, the title is shown in the browser tab when viewing a PDF inline.

```
use serde_json::json;
use spatie_pdf::PdfMetadata;

pdf.view("pdf.invoice", json!({"invoice": invoice}))
    .meta(PdfMetadata {
        title: Some("Invoice #123".into()),
        author: Some("Acme Corp".into()),
        subject: Some("Monthly invoice".into()),
        keywords: Some("invoice, acme, april".into()),
        creator: Some("My Application".into()),
        ..Default::default()
    })
    .save("/some/directory/invoice.pdf").await?;
```

All fields are optional. Only the fields you specify will be included in the new PDF information dictionary.

You can also set a creation date. It accepts a raw PDF date string; format application dates before building metadata.

```
use serde_json::json;
use spatie_pdf::PdfMetadata;

pdf.view("pdf.invoice", json!({"invoice": invoice}))
    .meta(PdfMetadata {
        title: Some("Invoice #123".into()),
        creation_date: Some(creation_date),
        ..Default::default()
    })
    .save("/some/directory/invoice.pdf").await?;
```

Metadata works with all drivers.

Conditional formatting
--------------------------------------------------------------------------------------------------------------------------

You can conditionally apply formatting options using the `when` and `unless` methods. This is useful when you want to change the PDF output based on some condition without breaking the method chain.

```
use serde_json::json;
use spatie_pdf::Format;

pdf.view("pdf.invoice", json!({"invoice": invoice}))
    .format(Format::A4)
    .when(invoice.is_landscape(), |pdf| pdf.landscape())
    .when(invoice.has_letterhead(), |pdf| {
        pdf.header_view("pdf.letterhead", json!({"company": invoice.company}))
    })
    .save("/some/directory/invoice.pdf").await?;
```

The `unless` method works the opposite way:

```
use serde_json::json;
use spatie_pdf::Unit;

pdf.view("pdf.report", json!({"report": report}))
    .unless(report.is_compact(), |pdf| {
        pdf.margins(20.0, 15.0, 20.0, 15.0, Unit::Millimeter)
    })
    .save("/some/directory/report.pdf").await?;
```

Debugging
-----------------------------------------------------------------------------------

You can use `dbg!` on the builder to inspect its current state:

```
use serde_json::json;
use spatie_pdf::Format;

dbg!(pdf.view("pdf.invoice", json!({"invoice": invoice}))
    .format(Format::A4)
    .landscape())
    .save("/some/directory/invoice.pdf").await?;
```

Encryption passwords are omitted from `Debug`. HTML and view data may still contain sensitive application data.

Background color
--------------------------------------------------------------------------------------------------------

All Chromium adapters request background printing. You can control color adjustment using CSS:

```
<style>
    html {
        -webkit-print-color-adjust: exact;
    }
</style>
```

Alternatively you can set `print-color-adjust` as `economy` to generate the PDF document in economy mode.

Or you can set a transparent background using Browsershot:

```
use serde_json::json;

pdf.view("test", json!({}))
    .browser_options(|options| {
        options.insert("omitBackground".into(), json!(true));
    })
    .save(target_path).await?;
```

 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)
