kallefrombosnia/tinypdf-php

Minimal PDF creation library for PHP 8.2+. Zero dependencies, strongly typed, clean code.

Installs: 0

Dependents: 0

Suggesters: 0

Security: 0

Stars: 1

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/kallefrombosnia/tinypdf-php

dev-main 2025-12-23 10:27 UTC

This package is auto-updated.

Last update: 2025-12-23 10:27:16 UTC


README

TinyPDF-PHP Preview

Tests Issues

Minimal PDF creation library for PHP 8.2+. Zero dependencies, strongly typed, clean code architecture.

Port of tinypdf from TypeScript to PHP.

Features

  • Create PDFs from scratch with zero dependencies
  • Strongly typed with PHP 8.2+ type declarations
  • Clean architecture with interfaces and value objects
  • Support for text, rectangles, lines, and JPEG images
  • Built-in markdown to PDF conversion
  • Text measurement and alignment
  • Color support (hex format)

Installation

composer require kallefrombosnia/tinypdf-php

Usage

Basic PDF Creation

use TinyPdf\TinyPdf;
use TinyPdf\TextOptions;
use TinyPdf\TextAlign;

$pdf = TinyPdf::create();

// Add a page (default US Letter: 612x792 points)
$pdf->page(function ($ctx) {
    // Add text
    $ctx->text('Hello World!', 50, 700, 24);

    // Text with options
    $ctx->text(
        'Centered text',
        50,
        650,
        16,
        new TextOptions(
            align: TextAlign::CENTER,
            width: 500,
            color: '#0066cc'
        )
    );

    // Draw a rectangle
    $ctx->rect(50, 600, 200, 100, '#ffcc00');

    // Draw a line
    $ctx->line(50, 580, 250, 580, '#000000', 2);
});

// Custom page size
$pdf->page(595, 842, function ($ctx) { // A4 size
    $ctx->text('A4 Page', 50, 700, 18);
});

// Build and save
$pdfContent = $pdf->build();
file_put_contents('output.pdf', $pdfContent);

Adding Images

$pdf = TinyPdf::create();

$pdf->page(function ($ctx) {
    $jpegData = file_get_contents('image.jpg');
    $ctx->image($jpegData, 50, 500, 200, 150);
});

file_put_contents('output.pdf', $pdf->build());

Markdown to PDF

use TinyPdf\MarkdownConverter;

$markdown = <<<MD
# Document Title

This is a paragraph with **bold** text.

## Section Header

- List item 1
- List item 2
- List item 3

1. Numbered item
2. Another item

---

Another paragraph after a horizontal rule.
MD;

$converter = new MarkdownConverter(
    width: 612,    // US Letter width
    height: 792,   // US Letter height
    margin: 72     // 1 inch margins
);

$pdfContent = $converter->convert($markdown);
file_put_contents('document.pdf', $pdfContent);

Text Measurement

use TinyPdf\TinyPdf;

// Measure text width before rendering
$width = TinyPdf::measureText('Hello World', 24);
echo "Text width: {$width} points\n";

Examples

The library includes several complete examples in the examples/ directory:

Running Examples

Run all examples at once:

php example.php

Or run individual examples:

# Basic text and shapes
php examples/basic/basic.php

# Professional invoice
php examples/invoice/invoice.php

# Markdown to PDF
php examples/markdown/markdown.php

# Multi-page document
php examples/multipage/multipage.php

Available Examples

  • Basic - Text rendering, shapes, colors, and alignment
  • Invoice - Professional invoice template with itemized billing
  • Markdown - Convert markdown documents to formatted PDFs
  • Multi-Page - Create documents with multiple pages and consistent styling

Each example includes its own README with detailed information.

API Reference

TinyPdf

Main factory class for creating PDF documents.

Methods

static function create(): PDFBuilderInterface

Create a new PDF builder

static function measureText(string $str, float $size): float

Measure text width in points

PDFBuilderInterface

Methods

function page(float|callable $widthOrFn, ?float $height = null, ?callable $fn = null): void

Add a page to the document

function build(): string

Build and return the final PDF content

function measureText(string $str, float $size): float

Measure text width in points

PageContextInterface

Context provided to page callbacks for drawing operations.

Methods

function text(string $str, float $x, float $y, float $size, ?TextOptions $opts = null): void

Render text at specified position

function rect(float $x, float $y, float $w, float $h, string $fill): void

Draw a filled rectangle

function line(float $x1, float $y1, float $x2, float $y2, string $stroke, float $lineWidth = 1.0): void

Draw a line

function image(string $jpegBytes, float $x, float $y, float $w, float $h): void

Render a JPEG image

TextOptions

Value object for text rendering options.

Constructor

new TextOptions(
    TextAlign $align = TextAlign::LEFT,
    ?float $width = null,
    string $color = '#000000'
)

Properties

public TextAlign $align

Text alignment (LEFT, CENTER, RIGHT)

public ?float $width

Width constraint for alignment

public string $color

Text color in hex format (e.g., '#ff0000')

MarkdownConverter

Convert markdown documents to PDF.

Constructor

new MarkdownConverter(
    float $width = 612,
    float $height = 792,
    float $margin = 72
)

Methods

function convert(string $markdown): string

Convert markdown to PDF content

Supported Markdown Features

  • Headers (H1-H3): #, ##, ###
  • Unordered lists: - or *
  • Ordered lists: 1., 2., etc.
  • Horizontal rules: ---, ***, ___
  • Paragraphs with automatic word wrapping
  • Blank lines for spacing

Coordinate System

PDF uses a coordinate system where:

  • Origin (0, 0) is at the bottom-left corner
  • X increases to the right
  • Y increases upward
  • Units are in points (1/72 inch)

Common page sizes:

  • US Letter: 612 x 792 points
  • A4: 595 x 842 points

Testing & Quality

TinyPDF-PHP includes comprehensive testing and static analysis.

Test Suite

Pest PHP - 69 tests with 105 assertions

  • 60 unit tests
  • 9 architecture tests
# Run all tests
composer test

# Run with coverage (requires Xdebug/PCOV)
composer test:coverage

# Run only architecture tests
./vendor/bin/pest --filter=Arch

Static Analysis

PHPStan Level 9 - Maximum strictness

# Run PHPStan
composer phpstan

# Run both PHPStan and tests
composer check

Architecture Tests

Pest Architecture plugin ensures:

  • No debugging functions (dd, dump, var_dump)
  • Strict types in all files
  • Classes are final or abstract
  • Interfaces have correct suffix
  • Enums are properly typed
  • Value objects are readonly
  • Internal classes not used outside
  • Contracts don't depend on implementations
  • No globals, eval, or goto

Coverage

  • PDF structure validation
  • Text rendering and alignment
  • Shape drawing (rectangles, lines)
  • JPEG image embedding
  • Markdown to PDF conversion
  • Text measurement accuracy
  • Type safety at PHPStan level 9
  • Clean architecture principles

See tests/README.md for detailed test documentation.

License

MIT

Credits

This is a PHP port of tinypdf by Lulzx.