Search by

andojoks / folio-studio-php

andojoks

Folio document engine for PHP — build pages programmatically, from SVG templates, array specs or Blade views, and export PDF + SVG. Zero runtime dependencies.

Package info

github.com/andojoks/folio-studio-php

pkg:composer/andojoks/folio-studio-php

Statistics

Installs: 2

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v1.1.0 2026-12-03 21:41 UTC

This package is auto-updated.

Last update: 2026-12-03 21:42:42 UTC


README

Folio document engine for PHP — build pages programmatically, from SVG templates, designer-project arrays, or Blade views, and export PDF + SVG. Zero runtime dependencies (PHP 8.1+, mbstring, zlib, json). A byte-parity port of the JavaScript engine in folio-studio-js/src.

Install

composer require andojoks/folio-studio-php

Quickstart

use Folio\Folio;

$doc = new Folio(['defaultFonts' => true, 'title' => 'Hello']);
$page = $doc->addPage();                       // A4 portrait, 48px margin
$page->text('Hello AV 123', 50, 100, ['size' => 24, 'font' => 'Poppins', 'bold' => true]);
$page->textBlock("Wrapped paragraph…", ['x' => 50, 'y' => 140, 'width' => 400, 'size' => 14]);
$page->table([
    'x' => 50, 'y' => 300, 'width' => 500,
    'columns' => [['key' => 'item', 'title' => 'Item', 'width' => '2*'], ['key' => 'qty', 'title' => 'Qty']],
    'rows' => [['item' => 'Widget', 'qty' => 3]],
]);
$doc->savePDF(__DIR__ . '/hello.pdf');         // or ->toPDF() / ->toSVG() / ->toSVGs()

Other entry points:

Folio::fromSVG($svg, $data);                   // SVG template + {{placeholders}} / {{#each}} / {{#if}}
Folio::fromTemplate('invoice', $data);         // certificate, letter, report-card, transcript, invoice, id-card
Spec::buildDoc($project, $data, ['defaultFonts' => true])['doc']; // folio-studio designer JSON (see below)
Folio::fromBlade('invoice.show', $data);       // Blade view rendering an <svg> root (see below)

Document options (pagination, validation, presets)

Folio::fromTemplate(), Spec::buildDoc() and new Folio() all accept the same options (identical names/values in folio-studio-js, folio-studio-builder and folio-studio-php). A preset selects a coherent combination; any option passed explicitly overrides the preset.

Option Values Default
validation 'strict' | 'lenient' 'strict'
pagination 'auto' | 'off' 'auto'
onOverflow 'error' | 'warn' | 'clip' 'error'
missingFont 'error' | 'warn' 'error'
  • pagination: 'auto' — content overflowing a page continues onto a new page: in designer specs, tables paginate (header repeats), text blocks taller than a page split across pages, and other elements move whole to the next page. 'off' disables automatic pagination; overflow is then governed by onOverflow.
  • onOverflow — what happens when content exceeds a page and pagination is off (or a single unbreakable element exceeds a page even with pagination on): 'error' throws Folio overflow: …; 'warn' renders what fits, warns, and marks the document overflowed ($doc->isOverflowed(), $doc->warnings()); 'clip' clips silently (the old behaviour, now explicit and only when chosen).
  • validation: 'strict' — throws named Folio validation error: … errors on NaN/infinite data, missing required fields, bad grade codes (report-card totals outside 0–100, transcript grades outside A–F), wrong types and missing {{placeholder}} data in SVG templates. 'lenient' coerces null/NaN to '' with a warning and continues. In designer specs a missing {{placeholder}} still renders '' (as in JS); strict validation there covers element structure and NaN data values.
  • missingFont: 'error' — throws Folio missing font: … when the requested family/weight/style is not registered at all; 'warn' falls back to a registered font and warns.

Presets:

Preset validation pagination onOverflow missingFont For
strict strict auto error error Production default
lenient lenient auto warn warn Forgiving imports
single-page strict off error error Certificates, ID cards — must fit one page; overflow fails loudly instead of silently clipping
draft lenient off clip warn Quick previews
$doc = Folio::fromTemplate('certificate', $data, ['preset' => 'single-page']);
$spec = Spec::buildDoc($project, $data, ['preset' => 'lenient', 'onOverflow' => 'error']);
$doc->warnings();      // string[] — validation / overflow / missing-font warnings
$doc->isOverflowed();  // true when onOverflow 'warn' fired

Designer specs (Spec::buildDoc)

A designer project is a plain array — the same JSON the folio-studio Designer edits (see Spec.php for the full schema):

$project = [
    'name' => 'Certificate', 'width' => 1122.5, 'height' => 793.7,
    'pages' => [[
        'id' => 'p1',
        'background' => ['type' => 'solid', 'color' => '#ffffff'],
        'elements' => [
            ['id' => 'e1', 'type' => 'rect', 'x' => 10, 'y' => 10, 'w' => 100, 'h' => 50,
             'fill' => ['type' => 'solid', 'color' => '#ff0000']],
            ['id' => 'e2', 'type' => 'text', 'x' => 10, 'y' => 70, 'w' => 200, 'autoH' => true,
             'text' => ['content' => 'Hi {{name}}!', 'font' => 'Poppins', 'size' => 16,
                        'weight' => 400, 'italic' => false, 'align' => 'left',
                        'lineHeight' => 1.3, 'letterSpacing' => 0, 'transform' => 'none',
                        'underline' => false, 'valign' => 'top']],
        ],
    ]],
    'data' => ['name' => 'Ada'], 'fonts' => [], 'assets' => [],
];
$result = Spec::buildDoc($project, ['name' => 'Ada'], ['defaultFonts' => true]);
$doc = $result['doc'];            // Folio document
$measured = $result['measured'];  // ['e1' => ['w' => 100, 'h' => 50], …]

Element types: rect, ellipse, line, polygon, path, text, image, table. A polygon either draws a regular/star shape from sides/inner, or a custom shape from points (relative to the bbox origin, scaled by the stored ow/oh bbox, as imported from a template). A path element draws its d the same way (stored bbox ow/oh maps onto x/y/w/h). Paints are ['type' => 'solid', 'color' => …], linear/radial gradients (stops: [['o' => 0, 'c' => '#000'], …], radial also takes cx/cy/r) or pattern (w, h, items — tile shapes replayed into the pattern). Text {{placeholders}} are bound from $data (same dialect as SVG templates); pass 'raw' => true to keep the placeholders in the text (for SVG template export).

Spec::buildDoc() builds the document on a fresh empty font registry, so pass 'defaultFonts' => true (or a shared 'fontRegistry') whenever the project lays out text — without it, any text throws "No fonts registered". Spec::newProject(), Spec::newPage() and Spec::newElement($type, $over) build projects/pages/elements with defaults (newElement('text', ['text' => ['content' => 'Hi']]) deep-merges the partial text override, keeping font/size/align defaults).

Laravel

Auto-discovery registers the service provider + Folio facade alias.

use Folio\Laravel\Facades\Folio;

// Controller: Blade view -> PDF download
$doc = Folio::fromBlade('invoice.show', ['invoice' => $invoice], ['title' => 'INV-1']);
return response()->folio($doc, 'inv-1.pdf');

Blade views output one <svg> root per page via the component (full example in examples/laravel):

<x-folio-page size="A4" background="#ffffff">
  <text x="48" y="70" font-size="34">{{ $invoice['number'] }}</text>
  @foreach ($invoice['items'] as $item)
    …
  @endforeach
</x-folio-page>

Config (php artisan vendor:publish --tag=folio-config):

// config/folio.php
return [
    'size' => 'A4', 'orientation' => 'portrait', 'margin' => 48,
    'title' => null, 'author' => null,
    'defaultFonts' => true,                    // bundled OFL fonts
    'fonts' => ['Brand' => ['regular' => resource_path('fonts/Brand-Regular.ttf')]],
    'font_aliases' => ['sans-serif' => 'Brand'],
    // 'preset' => 'strict',                    // document preset: strict | lenient | single-page | draft
];

Notes:

  • $data passed to fromBlade() is also bound to {{ }} placeholders left in the rendered SVG, so Blade-escaped @{{ }} sequences keep working with folio filters (upper, currency, date, …).
  • response()->folio($doc, $filename) / Response::folio(...) returns a PDF download response.
  • Outside Laravel, Folio::fromBlade() works with any renderer: Folio::setBladeRenderer(fn ($view, $data) => …) or the per-call $renderer argument.

Testing

Zero-dependency suite (works with plain php, no PHPUnit needed):

composer test          # php tests/run.php  — 624 assertions, must stay green

The suite differentially pins the port against the JS engine: committed corpora under tests/diff (toFixed, filters, fonts, layout, images, PDF/SVG/builder/spec/template references), golden PDFs/SVGs under tests/fixtures, plus hand-written unit tests including the Laravel integration (via Illuminate test doubles).

Remote images: PHP vs JS (intentional difference)

The two engines deliberately differ here, because PHP runs on a server that can fetch and JS runs in a browser that cannot fetch for PDF:

  • PHP (src/Render/Images.php, src/Builder/Canvas.php): remote http(s) image URLs are fetched (proxy-aware) and embedded as data URIs. SVG output embeds the image (larger file, offline-safe) and PDF export works with remote images. A template image asset that cannot be loaded (unreachable URL, missing file) is skipped, not failed (Kit::safeImage()); the document renders without that asset.
  • JS (src/render/images.js, src/builder.js): remote URLs are passed through into SVG (<image href="https://…">, the browser loads them), and PDF export throws "Remote images are not fetched" — pass image bytes or a data URI for PDF.

So: PHP SVG embeds where JS SVG references a URL, and PHP PDF works with remote images where JS PDF throws. Both behaviours are intentional and asserted in the two suites (PHP tests/run.php templates/image-assets, JS test/smoke.mjs §6).

License

MIT.