
# Laracards for Laravel Rust: editorial social cards and blog covers
<p align="center">
<a href="https://github.com/edulazaro/laracards-rust/actions/workflows/tests.yml"><img src="https://github.com/edulazaro/laracards-rust/actions/workflows/tests.yml/badge.svg" alt="Tests"></a>
<a href="https://crates.io/crates/laracards"><img src="https://img.shields.io/crates/v/laracards" alt="Crates.io"></a>
<a href="https://crates.io/crates/laracards"><img src="https://img.shields.io/crates/d/laracards" alt="Downloads"></a>
<a href="https://docs.rs/laracards"><img src="https://img.shields.io/docsrs/laracards" alt="Docs.rs"></a>
<a href="https://github.com/edulazaro/laracards-rust/blob/main/LICENSE.md"><img src="https://img.shields.io/crates/l/laracards" alt="License"></a>
</p>
Editorial social cards and blog covers for Laravel Rust. SVG templates rendered natively with
`resvg`, or image templates drawn with no SVG at all, text fitted with real font metrics, and
backgrounds that can be a flat colour, an Unsplash photo or an image you generated somewhere else.
No binary to install and no process to spawn.
```rust
Card::make("why-agents-are-more-than-a-model")
.template("post")
.data(json!({
"category_label": "DESARROLLO",
"title": "Por qué un agente de IA es mucho más que llamar a un modelo",
"author_name": "Edu Lazaro",
}))
.output(laravel::config().app.public_path("img/blog/why-agents.png"))
.generate(false)
.await?;
```
It is the port of [Laracards](https://github.com/edulazaro/laracards), the PHP package, to
[Laravel Rust](https://laravel.com/rust). **It targets Laravel Rust 0.1, which is in beta, and its
API follows the framework's changes until 1.0.** The names, the config keys and this document follow
the PHP package. Where Laravel Rust has no equivalent, the section says so, and the
[differences](#differences-from-the-php-package) are collected at the end.
## Installation
```bash
cargo add laracards
```
Register the service provider in `src/app.rs`, with the card sources you have:
```rust
use laracards::LaracardsServiceProvider;
use laravel::Application;
use crate::cards::BlogPostCards;
pub fn configure() -> ApplicationBuilder {
Application::configure().with_providers(|providers| {
providers.add(LaracardsServiceProvider::new().source("post", BlogPostCards));
})
}
```
The provider adds the configuration, the card generator, the renderer and the commands
(`cards:generate` and `laracards:publish`). It does not need any Laravel Rust feature, so it works with
`default-features = false`.
## Why
Generating an OG card usually ends up one of two ways: a headless browser, which drags Node and a few
hundred megabytes into every deploy, or a hand-rolled image script, which is fine until you want a
photo behind the text.
Laracards composes the card as an SVG and renders it in process. A background image is just another SVG
layer embedded as a data URI, which is what lets one template serve a flat card, a stock photo and an
AI-generated image without changing.
## The example template
```bash
laravel laracards:publish
```
writes `post.svg` into `resources/cards`, the `paths.templates` directory. The PHP package does this with
`vendor:publish --tag=laracards-templates`. The file is also the constant `laracards::templates::POST`.
## A card
```rust
use laracards::{Card, DataUri};
use serde_json::json;
Card::make("why-agents-are-more-than-a-model")
.template("post")
.data(json!({
"category_label": "DESARROLLO",
"title": "Por qué un agente de IA es mucho más que llamar a un modelo",
"author_name": "Edu Lazaro",
"date_formatted": "7 de agosto, 2026",
"brand_label": "ANDORRADEV.COM",
"logo_uri": DataUri::from_file(Some(laravel::config().app.public_path("img/logo.png").as_path())),
}))
.output(laravel::config().app.public_path("img/blog/why-agents.png"))
.generate(false)
.await?;
```
`data` takes a JSON object, which is the array of the PHP package: strings, numbers and null all work,
and `DataUri::from_file` returns an `Option`, which becomes `null` when the file is not there. A field
the template does not use is ignored, and a placeholder the card does not fill is removed.
`title` is declared as a fit rule in the config, so the generator turns it into `{{title_tspans}}` and
`{{title_font_size}}` for the template.
`generate(force)` returns the path it wrote, or `None` when the card was already up to date. PHP's
`generate()` has a default argument; Rust has not, so it is `generate(false)`.
## Size and format
Both are per template, with the values at the root of the config as the fallback. One project can serve
a 1200x630 open graph card and a square social card from the same command.
```rust
use laracards::{Format, LaracardsConfig, TemplateConfig};
cards.height = 630;
cards.format = Format::Png;
cards.quality = 85;
cards.templates.insert("photo".into(), TemplateConfig::new("photo.svg").format(Format::Jpg));
cards.templates.insert("square".into(), TemplateConfig::new("square.svg").width(1080).height(1080));
})
```
`Png`, `Jpg` and `Webp` are supported. PNG keeps a flat card crisp and lossless; behind a photograph,
`Jpg` is a fraction of the size. A JPEG is flattened onto white because it has no alpha. The `quality` is
the JPEG quality; WebP is written lossless (see the [differences](#differences-from-the-php-package)).
The extension of an explicit `.output()` path wins over the configured format, because asking for a
`.jpg` and getting a PNG named `.jpg` would be worse than any precedence rule. Size and format are part
of the fingerprint, so changing either regenerates the cards that use them.
An SVG whose own size has another shape than the configured one is stretched to the configured size, the
way `rsvg-convert --width --height` does. Draw the template at the size you generate it at.
## Backgrounds
Three drivers, one code path. All of them end as a local file embedded through `__BACKGROUND_URI__`.
```rust
card.background(None::<&str>); // template paints its own
card.background(laravel::config().app.public_path("img/ai/hero.png")); // anything already on disk
card.unsplash("mountain fog"); // downloaded once, then cached
```
`background` takes a path, a `Background` of your own, or `None`. The Unsplash driver caches by query, so
re-running the command does not hit the API and the same query always yields the same card. Delete the
cached file to ask for a different photo. For another orientation than landscape, pass the driver:
```rust
card.background(UnsplashBackground::new("mountain fog").orientation("portrait"));
```
The access key is `backgrounds.unsplash.access_key`, read from `UNSPLASH_ACCESS_KEY`. A card with no
key gets no background and a warning through `tracing`, instead of an error.
A path that is not a file is an error, not a missing background: the card fails with
`Laracards: the background '...' does not exist.`, and `cards:generate` prints it as a `[FAIL]` line
and carries on with the other cards. The path is used as given, so a relative one is relative to the
directory the process runs in. `laravel::config().app.public_path("img/ai/hero.png")` is the public
directory of the app, whatever that directory is.
To write your own driver, implement `Background`: `resolve` returns the path of a local image, or `None`,
and `fingerprint` is what the manifest compares.
## Sources and the command
A `CardSource` maps a content collection to cards. One per kind of content, instead of one command per
kind of content.
```rust
use async_trait::async_trait;
use laracards::{Card, CardSource};
use serde_json::json;
pub struct BlogPostCards;
#[async_trait]
impl CardSource for BlogPostCards {
async fn cards(&self) -> laravel::Result<Vec<Card>> {
let posts = Post::query().all().await?;
Ok(posts
.iter()
.map(|post| {
Card::make(post.slug.clone())
.template("post")
.data(json!({
"title": post.title,
"category_label": post.category.to_uppercase(),
"author_name": post.author,
"date_formatted": post.date_formatted(),
}))
.background(post.cover.clone().map(|cover| laravel::config().app.public_path(cover)))
.output(laravel::config().app.public_path(format!("img/blog/{}.png", post.slug)))
})
.collect())
}
}
```
Register it on the provider, as above, and run:
```bash
laravel cards:generate
laravel cards:generate --source=post --only=some-slug --force
laravel cards:generate --dry-run
```
`--source` and `--only` can be given more than once. The command prints one line per card, and exits with
a failure when any card failed, after trying the rest:
```
post
[OK] hello - 41.2 KB
[SKIP] world (up to date)
[FAIL] broken - Laracards: template 'nope' is not configured.
Generated 1, skipped 1, failed 1.
```
### From another package
PHP packages add their class to `laracards.sources` from their provider. A source is code here, so a
package registers it with `laracards::source`, from the `boot` of its own provider, which runs after every
provider has registered:
```rust
async fn boot(&self, _app: &Container) -> laravel::Result<()> {
laracards::source("larablog", PostCards).await
}
```
A source with the same name replaces the earlier one. `laracards::sources()` lists them.
## Placing a block whose height you do not know
A headline can take one line or three, and SVG cannot do arithmetic, so the position has to be computed
before the template sees it. Two things come out of every fit rule.
`anchor` decides which line lands on `baseline`. The default, `Anchor::Top`, puts the first line there.
With `Anchor::Bottom`, the last line does, which keeps a short headline and a long one sitting on the same
rule instead of drifting down the card.
```rust
.fit(
"title",
FitRule::new()
.font("default")
.x(80)
.max_width(1040)
.max_lines(3)
.sizes([82, 72, 64, 56, 48])
.line_height(1.17)
.anchor(Anchor::Bottom)
.baseline(434),
)
```
The template reads the result from `{{title_baseline}}`, and everything that has to travel with the
headline goes in a group translated to it:
```xml
<g transform="translate(0 {{title_baseline}})">
<text x="80" y="-78" font-size="19" fill="#eab308">{{category_label}}</text>
<text x="80" y="0" font-size="{{title_font_size}}">{{title_tspans}}</text>
</g>
```
Every block also exposes `{key}_bottom`, which is where it actually ends. That is how a subtitle hangs off
a headline of unknown height and keeps the same gap in every card:
```xml
<g transform="translate(0 {{title_bottom}})">
<text x="80" y="52" font-size="{{subtitle_font_size}}">{{subtitle_tspans}}</text>
</g>
```
Alongside those, a fit rule also fills `{key}_tspans`, `{key}_font_size` and `{key}_line_count`, and
`{key}_highlights` when it asks for [highlighted lines](#highlighted-lines).
A template is plain text with `{{key}}` placeholders and `__KEY__` for values that are not text, such as
data URIs. `{{#key}}...{{/key}}` is a section that disappears when the key has no value, which an optional
layer needs: an `<image>` with an empty `href` makes a renderer give up. This is the package's own syntax,
the one of the PHP package, and not MiniJinja.
## Highlighted lines
A headline set on bars of colour, one per line and as wide as that line's text, is the marker-pen look of a
lot of blog covers. SVG cannot draw it on its own, because it cannot measure its own text, so the fit rule
does it: add `highlight` and the template gets `{key}_highlights`, one `<rect>` per line.
```rust
.fit(
"title",
FitRule::new()
.font("title")
.x(600)
.max_width(1000)
.max_lines(3)
.sizes([80, 70, 60, 52])
.line_height(1.45)
.baseline(150)
.align(Align::Center)
.highlight(Highlight::padded(12, 10)),
)
```
```xml
<g fill="{{accent}}">{{title_highlights}}</g>
<text x="600" y="{{title_baseline}}" text-anchor="middle" font-size="{{title_font_size}}" fill="#fff">{{title_tspans}}</text>
```
The boxes go before the text in the template, so the text lands on top. Their height comes from the face's
real ascent and descent plus `padding_y`, and their width from the measured line plus `padding_x` on each
side. `align` tells them how the text is anchored on `x`, so a template that centres with
`text-anchor="middle"` needs `Align::Center` too. `Highlight::default()` is the PHP `'highlight' => true`:
10 and 6 pixels. A block needs a `baseline`, or a place in a `stack`, for its boxes to be placed.
In an image template the boxes are drawn behind each line, in the colour given as
`Highlight::padded(12, 6).color("#2563eb")`.
## Image templates, no SVG
A template can also be a PNG, JPG or WebP. Laracards sees the extension and draws the text straight onto
the image, so no SVG is involved. It is the way to keep an existing design that lives in an image.
An image carries no positions, so the fit rules say where each block goes and how it looks. They are the
same rules an SVG template uses, plus the two things an SVG would otherwise hold itself: `color` (`#rgb`,
`#rrggbb`, `#rrggbbaa`, `rgb()` or `rgba()`, white by default) and `align` (`Left`, `Center` or `Right`,
`Left` by default). With `Center`, `x` is the centre of each line; with `Right`, its right edge.
```rust
cards.templates.insert(
"og".into(),
TemplateConfig::new("og.png").fit(
"title",
FitRule::new()
.font("bold")
.x(600)
.max_width(480)
.max_lines(3)
.sizes([44])
.line_height(1.2)
.color("rgba(255,255,255,0.9)")
.align(Align::Center)
.baseline(300),
),
);
```
Every block needs a place: a `baseline`, as above, or a spot in a `stack`. A stack measures a group of
blocks and centres the whole group on `center_y`, each block below the previous one with `gap` between
them. A block that comes out empty drops out, so a card without a subtitle keeps its title centred:
```rust
.stack(Stack::new(["title", "subtitle"]).center_y(315).gap(34))
```
`stack` works for SVG templates too: it fills `{key}_baseline` and `{key}_bottom` for the stacked blocks.
The card background, if the card has one, is drawn under the image, so a template with transparent areas
works as an overlay on a photo, just as `__BACKGROUND_URI__` does in an SVG. A template of another size is
scaled to cover the card and cropped from the centre. Size, format, the manifest and the command behave
exactly as with SVG templates. For image templates the template config is part of the fingerprint, since
that is where colours and positions live: changing a colour regenerates the cards drawn with it.
## Text fitting is measured, not estimated
Wrapping by character count gives every glyph the same budget, so a title made of wide words silently runs
off the card. Laracards measures against the same font file, picks the largest size from the candidate list
that fits in the given number of lines, and only ellipsizes when even the smallest one does not.
For a 1040px column at 82px:
| `MMMMMMMM MMMMMMMM MMMMMMMM` | 2 lines, 1672px wide, 632px off the card | 3 lines, 818px |
| `Indemnizaciones millonarias por incumplimiento…` | 5 lines, truncated to 3 with an ellipsis | 3 lines at 56px, full title |
The PHP package measures through GD. This one reads the face with `ttf-parser`: the advance of every
glyph plus the pair kerning of the font's `kern` table, in the pixel size an SVG `font-size` means. A face
that only kerns through GPOS measures unkerned, which is slightly wider and so errs on the safe side. The
tests check the measurement against what the renderer actually draws.
## Regeneration is decided by content, not by file existence
Every generated card records a fingerprint of its template, payload and background in a manifest. Change
the title, move the publish date, swap the photo, and the card regenerates by itself on the next run.
Nothing changes, nothing is rewritten.
This is what removes the "delete the PNG by hand because the date is printed on it" step.
## Fonts
The renderer is `resvg`, as a library, so it has no fontconfig to depend on. It knows the fonts you give it:
every face under `fonts`, the files in `renderers.resvg.font_files`, and the fonts installed on the machine
unless you turn that off.
```rust
cards.fonts.insert("default".into(), "public/fonts/Lato-Bold.ttf".into());
cards.renderers.resvg.font_files = vec!["public/fonts/Lato-Regular.ttf".into()];
cards.renderers.resvg.system_fonts = false;
```
The faces under `fonts` are the ones text is measured with, and they are loaded into the renderer too, so
the measurement cannot drift from the render. The SVG still names its font with `font-family`, and that name
has to be the family of one of those files. The generic families (`sans-serif`, `serif`, `monospace`,
`cursive`, `fantasy`) that nothing installed answers to fall back to the first font file, so a template
asking for `-apple-system, Helvetica, Arial, sans-serif` still draws on a container with no fonts at all.
Paths that are not absolute start at the application's base path.
## Generate locally, commit the output
Cards are static. Generating them on request means a render on the hot path. Run the command when content
changes and commit the images.
## Configuration
Everything lives in `LaracardsConfig`, a configuration section. Only the Unsplash key reads the
environment; the rest describes how the application draws its cards and is set in `src/app.rs`:
| `width`, `height` | `1200`, `630` | The size of a card, unless its template says otherwise |
| `format` | `Format::Png` | `Png`, `Jpg` or `Webp` |
| `quality` | `85` | The JPEG quality |
| `paths.templates` | `resources/cards` | Where the templates live |
| `paths.output` | `public/img/cards` | Where a card without an output path is written |
| `paths.manifest` | `storage/app/laracards/manifest.json` | The fingerprints of the generated cards |
| `fonts` | `default` is `public/fonts/Lato-Bold.ttf` | The faces text is measured with, by name |
| `renderers.resvg.font_files` | `[]` | More font files for the renderer |
| `renderers.resvg.system_fonts` | `true` | Also load the fonts installed on the machine |
| `backgrounds.unsplash.access_key` | `None` | From `UNSPLASH_ACCESS_KEY` |
| `backgrounds.unsplash.cache` | `storage/app/laracards/backgrounds` | Where downloaded photos are kept |
| `templates` | `post` | The templates, by name |
A template is a `TemplateConfig`: a `file`, optional `width`, `height` and `format`, its `fit` rules and an
optional `stack`. A `FitRule` has the keys of the PHP package with the same defaults: `font` (`default`),
`x` (`80`), `max_width` (`1040`), `max_lines` (`3`), `sizes` (`72, 64, 56, 48`), `line_height` (`1.17`),
`anchor` (`Top`), `baseline`, `color` (`#ffffff`), `align` (`Left`) and `highlight`. A `Stack` has `fields`,
`center_y` (`315`) and `gap` (`24`).
## Testing
The package's own tests use the pattern the Laravel Rust guide describes for packages: a
`tests/common/mod.rs` that builds an application with `for_testing`, `#[laravel::test(app = ..)]` on each
test, `client::fake()` for Unsplash, and real renders. They write real PNGs and assert their size and their
pixels, and they check text fitting against a bundled DejaVu font kept in `tests/fonts`, which is not part
of the published crate.
In your own tests, replace the renderer to capture the SVG instead of drawing it:
```rust
struct Capture(Mutex<Vec<String>>);
impl Renderer for Capture {
fn render(&self, svg: &str, width: u32, height: u32) -> Result<RgbaImage, RenderFailed> {
self.0.lock().unwrap().push(svg.to_owned());
Ok(RgbaImage::new(width, height))
}
}
#[laravel::test]
async fn it_composes_the_card(app: Application) -> laravel::Result<()> {
let capture = Arc::new(Capture(Mutex::default()));
app.swap_as(Arc::clone(&capture) as Arc<dyn Renderer>);
Card::make("hello").data(json!({ "title": "Hello" })).generate(false).await?;
assert!(capture.0.lock().unwrap()[0].contains("Hello"));
Ok(())
}
```
Swap it before the first card is generated, because the generator is built on first use.
## Differences from the PHP package
- **The renderer is native.** There is no `rsvg-convert` or `resvg` binary and no process. The `renderer`
key and `renderers.rsvg` are gone, and `renderers.resvg` keeps `font_files` (the `--use-font-file` of the
binary) and adds `system_fonts`. The `binary` and `env` keys, which pointed at a process and its
`FONTCONFIG_FILE`, have nothing to point at. There is no fontconfig: fonts come from the files you list.
- **The `Renderer` contract takes the SVG text and returns the pixels**, instead of reading an SVG file and
writing a PNG, so there is no temporary SVG and no `paths.temp`. `available()` is kept, and is always true
for the native renderer.
- **Image templates are drawn with `tiny-skia`, the glyph outlines of the face filled onto the image,** instead
of with GD. Alpha is 0 to 255 opacity, the opposite of GD's 0 to 127 transparency, so `Color::parse` returns
`[255, 255, 255, 230]` for `rgba(255,255,255,0.9)`, where PHP returns an alpha of 13.
- **Text is measured in pixels with `ttf-parser`**, not in points with GD, so the 72/96 conversion of the PHP
package is gone. Widths are rounded up, so a line that measures as fitting always does.
- **WebP is lossless.** The encoder of the `image` crate has no lossy WebP, so `quality` only applies to JPEG
and a WebP card is larger than the PHP one at the same size.
- **Config is typed.** Templates, fit rules, stacks and highlights are structs with builders, and an
`highlight: true` is `Highlight::default()`. Fit rules are kept in the order they were added. The `sources`
key is not config, because a source is code: register it on the provider or with `laracards::source`.
- **Only `UNSPLASH_ACCESS_KEY` reads the environment**, as in the PHP config. The `LARACARDS_*` variables of the
renderer are gone with the renderer.
- **`Card::data` takes a JSON value**, `json!({ ... })` for the PHP array, and ignores anything that is not an
object. A `Background` is a path, a driver or `None` (`null`). `unsplash(query)` has no orientation
argument: pass `UnsplashBackground::new(query).orientation(..)` to `background`. `generate(force)` has no
default argument.
- **A local background that does not exist is an error.** The PHP `LocalBackground` returns `null` for a path
that is not a file, and the card is drawn without a background, with no warning. Here `resolve` fails, and
the card fails with `Laracards: the background '<path>' does not exist.`. A card with no background at all
(`None`) is unchanged, and so is the Unsplash driver, which still skips with a warning when it has no key.
- **A `CardSource` returns a `Vec` and is `async`**, instead of an iterable, so it can read the database. A
source has to build every card of the collection before the command runs any.
- **`vendor:publish --tag=laracards-templates` is `laracards:publish`**, a command of the package, because
Laravel Rust 0.1 has no `vendor:publish`. There is nothing to publish for the config.
- **An SVG template is stretched to the configured size** like `rsvg-convert --width --height`, rather than
scaled to fit like the `resvg` binary does.
## Contributing
Contributions are welcome! Please fork the repo, add tests, and submit a PR.
## Sponsors
Laracards for Laravel Rust is supported by the following sponsors. Thank you for keeping it growing:
<p>
<a href="https://kenodo.com"><img src="art/logo-kenodo.png" width="24" alt="Kenodo"></a> <a href="https://kenodo.com">Kenodo</a>
<a href="https://andorradev.com"><img src="art/logo-andorradev.png" width="24" alt="AndorraDev"></a> <a href="https://andorradev.com">AndorraDev</a>
</p>
## Author
Created by [Edu Lazaro](https://edulazaro.com)
## License
Laracards for Laravel Rust is open-sourced software licensed under the [MIT license](LICENSE.md).