sim-pdf / sim-pdf-libs
Advanced PDF generation library for Laravel with multi-page support, custom page breaks, headers/footers, and comprehensive styling
Requires
- php: ^8.1
- dompdf/dompdf: ^3.0.1
- illuminate/support: ^9.0|^10.0|^11.0|^12.0
Requires (Dev)
- orchestra/testbench: ^8.0|^9.0|^10.0
- phpunit/phpunit: ^9.5|^10.0|^11.0|^12.0
This package is auto-updated.
Last update: 2026-08-07 10:25:26 UTC
README
A comprehensive PDF generation library for Laravel and PHP applications with advanced features including multi-page support, custom page breaks, headers/footers, watermarks, bookmarks, and full styling capabilities.
๐ Features
- ๐ Multi-page Support - Handle large documents with automatic pagination
- ๐ Custom Page Breaks - Break pages anywhere you want, even within tables
- ๐ Table Pagination - Smart table breaking with repeated headers (
<thead>) - ๐ข Page Numbering - Automatic dynamic page numbering (
Page {PAGE_NUM} of {PAGE_COUNT}) rendered via native Dompdf canvas scripts - ๐ Headers & Footers - Customizable headers and footers with automated
@pagetop/bottom margin calculation to eliminate text overlap - ๐จ Advanced Styling - Full CSS support including Microsoft Word-like formatting
- ๐ง Watermarks - Add opacity-controlled, rotated CSS watermarks to your PDFs
- ๐ Bookmarks - Create PDF bookmarks for navigation
- ๐ Metadata - Set PDF metadata (title, author, subject, etc.)
- ๐ก๏ธ Typed Exceptions - Custom PdfGenerationException thrown on invalid paper sizes, orientation errors, or file save failures
- โก Performance & Octane Ready - Transient container bindings (SimPdfServiceProvider) and explicit
resetState()to prevent cross-request state pollution in long-running processes (Swoole, Octane, Queue workers)
๐ Installation
Packagist Installation (Recommended)
# Install from Packagist composer require sim-pdf/sim-pdf-libs # Publish config (optional) php artisan vendor:publish --provider="SimPdf\SimPdfLibs\SimPdfServiceProvider" --tag="config"
Git Installation
# Install from Git repository
composer config repositories.sim-pdf vcs https://github.com/5u00n/sim-pdf-libs
composer require sim-pdf/sim-pdf-libs:dev-main
For step-by-step setup guides, refer to INSTALLATION.md.
๐ฏ Quick Start
Basic PDF (3 lines using Facade)
use SimPdf\SimPdfLibs\Facades\SimPdf; $html = '<h1>Hello World</h1><p>This is a PDF!</p>'; return SimPdf::loadHtml($html)->download('document.pdf');
Global Helper (simpdf())
// Use the ultra-concise global helper function anywhere in your app: return simpdf('<h1>Hello World</h1>')->setPaper('A4')->download('document.pdf');
Save Directly to Storage Disk (saveToDisk())
// Save to AWS S3, Google Cloud, or local Laravel Storage disk: SimPdf::loadHtml($html)->saveToDisk('invoices/2026/inv-101.pdf', 's3');
Laravel Blade Directives (@pageBreak, @noBreak)
<h1>Section 1</h1> @pageBreak <h1>Section 2</h1> @noBreak <div>This block will not be split across page breaks</div> @endNoBreak
๐ฏ When to Use SimPDF
โ Perfect For:
- ๐ Reports & Invoices - Professional business documents
- ๐ Contracts & Legal Docs - Multi-page documents with headers/footers
- ๐ Manuals & Guides - Large documents with bookmarks and page numbers
- ๐ Data Reports - Tables with pagination and custom breaks
- ๐จ Styled Documents - Microsoft Word-like formatting
- ๐ Forms & Applications - Complex layouts with styling
- ๐ Catalogs & Brochures - Multi-page marketing materials
- ๐ Financial Statements - Professional financial documents
โ Not Ideal For:
- ๐ผ๏ธ Image-heavy PDFs - Use specialized image-to-PDF tools
- ๐ฑ Interactive PDFs - Use Adobe Acrobat or similar
- ๐ฌ Video/Audio PDFs - Use multimedia PDF tools
- ๐ Complex Charts - Use chart-specific libraries first
๐ Best Use Cases:
1. Business Reports
// Perfect for monthly/quarterly reports SimPdf::loadHtml($reportHtml) ->setPaper('A4', 'portrait') ->enablePageNumbers() ->setHeader('Monthly Report - ' . date('F Y')) ->setFooter('Confidential - Page {PAGE_NUM}') ->download('monthly-report.pdf');
2. Invoice Generation
// Perfect for invoices with line items SimPdf::loadHtml($invoiceHtml) ->breakTable(['repeat_header' => true]) ->setHeader('INVOICE #' . $invoiceNumber) ->setFooter('Payment due within 30 days') ->download('invoice.pdf');
3. User Manuals
// Perfect for documentation with bookmarks SimPdf::loadHtml($manualHtml) ->addBookmark('Introduction', 1) ->addBookmark('Installation', 1) ->addBookmark('Configuration', 1) ->addBookmark('Troubleshooting', 1) ->enablePageNumbers() ->download('user-manual.pdf');
๐ Real-World Usage Examples
1. Employee Report Card
// Perfect for HR reports with multiple pages $html = view('reports.employee-card', [ 'employee' => $employee, 'performance' => $performanceData, 'goals' => $goals ])->render(); return SimPdf::loadHtml($html) ->setPaper('A4', 'portrait') ->enablePageNumbers(['position' => 'bottom-center']) ->setHeader('Employee Performance Report') ->setFooter('Confidential - HR Department') ->addWatermark('CONFIDENTIAL', ['opacity' => 0.1]) ->download('employee-report-' . $employee->id . '.pdf');
2. Product Catalog
// Perfect for e-commerce catalogs $html = view('catalog.products', [ 'products' => $products, 'categories' => $categories ])->render(); return SimPdf::loadHtml($html) ->setPaper('A4', 'portrait') ->breakTable(['repeat_header' => true, 'min_rows' => 3]) ->setHeader('Product Catalog 2026') ->setFooter('Visit our website for more products') ->addBookmark('Electronics', 1) ->addBookmark('Clothing', 1) ->addBookmark('Home & Garden', 1) ->download('product-catalog.pdf');
3. Financial Statement
// Perfect for financial documents $html = view('financial.statement', [ 'revenue' => $revenueData, 'expenses' => $expensesData, 'balance' => $balanceSheet ])->render(); return SimPdf::loadHtml($html) ->setPaper('A4', 'landscape') ->breakTable(['repeat_header' => true]) ->setHeader('Financial Statement - Q' . $quarter . ' ' . $year) ->setFooter('Prepared by: ' . auth()->user()->name) ->addWatermark('DRAFT', ['opacity' => 0.3, 'color' => '#ff0000']) ->setMetadata([ 'Title' => 'Financial Statement', 'Author' => auth()->user()->name, 'Subject' => 'Quarterly Financial Report' ]) ->download('financial-statement-q' . $quarter . '.pdf');
4. Contract Document
// Perfect for legal documents $html = view('contracts.agreement', [ 'contract' => $contract, 'parties' => $parties, 'terms' => $terms ])->render(); return SimPdf::loadHtml($html) ->setPaper('A4', 'portrait') ->addPageBreak('page', ['before' => '.contract-section']) ->setHeader('Service Agreement - ' . $contract->number) ->setFooter('Page {PAGE_NUM} of {PAGE_COUNT} - Legal Document') ->addBookmark('Parties', 1) ->addBookmark('Terms & Conditions', 1) ->addBookmark('Payment Terms', 1) ->addBookmark('Signatures', 1) ->download('contract-' . $contract->number . '.pdf');
๐ Advanced Usage
Multi-page PDF with Headers and Footers
$html = ' <!DOCTYPE html> <html> <head><title>Multi-page Document</title></head> <body> <h1>Page 1</h1> <p>Content for page 1...</p> <div class="page-break"></div> <h1>Page 2</h1> <p>Content for page 2...</p> </body> </html>'; SimPdf::loadHtml($html) ->setPaper('A4', 'portrait') ->enablePageNumbers([ 'position' => 'bottom-right', 'format' => 'Page {PAGE_NUM} of {PAGE_COUNT}' ]) ->setHeader('<h3>Company Header</h3>', [ 'height' => '60px', 'background' => '#f8f9fa' ]) ->setFooter('<p>ยฉ 2026 Company Name</p>', [ 'height' => '40px', 'background' => '#f8f9fa' ]) ->download('multi-page-document.pdf');
Advanced Table with Custom Breaks
$html = ' <table class="breakable-table"> <thead> <tr> <th>Name</th> <th>Email</th> <th>Department</th> </tr> </thead> <tbody> <!-- Large table data --> </tbody> </table>'; SimPdf::loadHtml($html) ->setPaper('A4', 'portrait') ->breakTable([ 'repeat_header' => true, 'min_rows' => 5, 'max_rows' => 20 ]) ->addStyle(' .breakable-table { page-break-inside: auto; } .breakable-table thead { display: table-header-group; } .breakable-table tbody { page-break-inside: auto; } .breakable-table tr { page-break-inside: avoid; } ') ->download('table-document.pdf');
Advanced Features
Custom Page Breaks
// Break before specific element SimPdf::loadHtml($html) ->addPageBreak('page', ['before' => '<h2>New Section</h2>']) ->download('document.pdf'); // Break after specific element SimPdf::loadHtml($html) ->addPageBreak('page', ['after' => '<div class="section-end"></div>']) ->download('document.pdf'); // Avoid breaking inside elements SimPdf::loadHtml($html) ->addPageBreak('avoid', ['element' => '.no-break']) ->download('document.pdf');
Watermarks and Bookmarks
SimPdf::loadHtml($html) ->addWatermark('CONFIDENTIAL', [ 'opacity' => 0.3, 'font-size' => '48px', 'color' => '#ff0000', 'rotation' => -45, 'position' => 'center' ]) ->addBookmark('Introduction', 1) ->addBookmark('Details', 1) ->addBookmark('Summary', 1) ->download('document.pdf');
Metadata and Styling
SimPdf::loadHtml($html) ->setMetadata([ 'Title' => 'My Document', 'Author' => 'John Doe', 'Subject' => 'Important Document', 'Keywords' => 'PDF, Laravel, Document' ]) ->addStyle(' body { font-family: Arial, sans-serif; } h1 { color: #2c3e50; } .highlight { background-color: #ffff00; } ') ->download('document.pdf');
โ๏ธ Configuration
The package comes with a comprehensive configuration file at config/simpdf.php. You can customize:
- Default paper size and orientation
- Font settings and caching
- Page break behavior
- Header and footer defaults
- Page numbering format
- Watermark settings
- Performance options
- Security settings
๐๏ธ Laravel Integration
Controller Example
<?php namespace App\Http\Controllers; use SimPdf\SimPdfLibs\Facades\SimPdf; class PdfController extends Controller { public function generateReport() { $html = view('pdf.report', [ 'data' => $this->getReportData() ])->render(); return SimPdf::loadHtml($html) ->setPaper('A4', 'portrait') ->enablePageNumbers() ->setHeader('Report Header') ->setFooter('Report Footer') ->download('report.pdf'); } }
Blade Template
<!DOCTYPE html> <html> <head> <title>Report</title> <style> .page-break { page-break-before: always; } .no-break { page-break-inside: avoid; } </style> </head> <body> <h1>Report Title</h1> @foreach($data as $section) <div class="section"> <h2>{{ $section['title'] }}</h2> <p>{{ $section['content'] }}</p> </div> @if(!$loop->last) <div class="page-break"></div> @endif @endforeach </body> </html>
๐ API Reference
Main Methods
loadHtml(string $html)- Load HTML contentsetPaper(string $paper, string $orientation)- Set paper size and orientationsetOptions(array $options)- Set PDF generation optionsaddPageBreak(string $type, array $options)- Add custom page breakssetHeader(string $content, array $options)- Set header contentsetFooter(string $content, array $options)- Set footer contentenablePageNumbers(array $options)- Enable page numberingaddStyle(string $css)- Add custom CSSaddWatermark(string $text, array $options)- Add watermarkaddBookmark(string $title, int $level)- Add bookmarksetMetadata(array $metadata)- Set PDF metadatabreakTable(array $options)- Configure table breakingbreakRow(array $options)- Configure row breakingresetState()- Reset instance state for long-running processes (Octane/Swoole)
Output Methods
output()- Get PDF as raw string bytessave(string $path)- Save PDF to file (throwsPdfGenerationExceptionon failure)download(string $filename)- ReturnsIlluminate\Http\Responsein Laravel or sends download headers in standalone PHPstream()- ReturnsIlluminate\Http\Responsein Laravel or streams PDF inline
โก Performance & Best Practices
๐ Performance Tips:
1. Large Documents
// For documents with 100+ pages SimPdf::loadHtml($html) ->setOptions([ 'enable_css_float' => false, // Disable for better performance 'enable_html5_parser' => true, 'dpi' => 72, // Lower DPI for faster rendering 'isFontSubsettingEnabled' => true // Reduce font file size ]) ->download('large-document.pdf');
2. Memory Management
// For memory-intensive operations ini_set('memory_limit', '512M'); ini_set('max_execution_time', 300); SimPdf::loadHtml($html) ->setOptions(['isPhpEnabled' => false]) // Disable PHP for security ->download('document.pdf');
3. Caching Styles
// Cache frequently used styles $commonStyles = ' .header { font-size: 14px; font-weight: bold; } .footer { font-size: 10px; color: #666; } .page-break { page-break-before: always; } '; SimPdf::loadHtml($html) ->addStyle($commonStyles) ->download('document.pdf');
๐ฏ Best Practices:
1. Use Blade Templates
// โ Good: Use Blade templates $html = view('pdf.report', compact('data'))->render(); // โ Avoid: Inline HTML in controllers $html = '<html><body><h1>Report</h1>...</body></html>';
2. Optimize Images
// โ Good: Optimize images before PDF generation $html = '<img src="' . asset('images/optimized-logo.png') . '" width="200">'; // โ Avoid: Large unoptimized images $html = '<img src="' . asset('images/huge-logo.jpg') . '">';
3. Use CSS Classes for Page Breaks
// โ Good: Use CSS classes $html = '<div class="page-break"></div>'; // โ Avoid: Inline styles $html = '<div style="page-break-before: always;"></div>';
4. Handle Errors Gracefully
try { return SimPdf::loadHtml($html)->download('document.pdf'); } catch (\SimPdf\SimPdfLibs\Exceptions\PdfGenerationException $e) { Log::error('PDF Generation Failed: ' . $e->getMessage()); return redirect()->back()->with('error', 'Failed to generate PDF: ' . $e->getMessage()); }
๐ Performance Benchmarks:
| Document Type | Pages | Size | Generation Time |
|---|---|---|---|
| Simple Report | 1-5 | < 1MB | < 2 seconds |
| Business Report | 10-20 | 2-5MB | 3-8 seconds |
| Large Manual | 50+ | 10-20MB | 15-30 seconds |
| Data Export | 100+ | 50MB+ | 30-60 seconds |
๐ Requirements
- PHP 8.1 or higher (recommended PHP 8.2+)
- Laravel 9.0 or higher (supports Laravel 9, 10, 11, 12)
- DomPDF 3.0.1 or higher
๐ Repository File Navigator
Explore all repository components, documentation, source code, and community templates directly:
๐ Documentation & Governance
- ๐ LICENSE - Official MIT License file
- ๐ก๏ธ SECURITY.md - Security disclosure policy and configuration hardening
- ๐ค CONTRIBUTING.md - Contribution guidelines, coding standards, and PR process
- ๐ CODE_OF_CONDUCT.md - Contributor Covenant Code of Conduct
- ๐ CHANGELOG.md - Version history and release notes
- ๐ INSTALLATION.md - Installation methods and framework compatibility
- ๐๏ธ PROJECT_STRUCTURE.md - Structural map of package files
โ๏ธ Configuration
- ๐ง config/simpdf.php - Full package configuration (fonts, paper size, margins, performance)
๐ป Core Source Code (src/)
- ๐ src/SimPdfServiceProvider.php - Service provider with transient container bindings
- ๐ญ src/Facades/SimPdf.php - Laravel Facade accessor
- ๐ src/Contracts/PdfGeneratorInterface.php - Core contract interface
- โ๏ธ src/Services/PdfGeneratorService.php - Primary PDF generation engine
- ๐ src/Services/HeaderFooterService.php - Header/footer CSS positioning & margin calculation
- ๐ src/Services/PageBreakService.php - Page break controls and canvas page numbering
- ๐จ src/Services/StylingService.php - Watermarks, CSS styling, and bookmarks
- ๐ ๏ธ src/Helpers/PdfHelper.php - Filename sanitization, memory limit calculation, and HTML helpers
- ๐จ src/Exceptions/PdfGenerationException.php - Package exception definitions
๐ก Examples & Resources
- ๐ examples/laravel-controller-example.php - Complete Laravel Controller implementation
- ๐ examples/existing-code-integration.php - Integration with existing Laravel codebases
- ๐ examples/basic-usage.php - Basic standalone PHP example
- ๐ examples/advanced-usage.php - Advanced multi-page standalone PHP example
- ๐จ resources/views/pdf/basic-template.blade.php - Starter Blade PDF template
- ๐ resources/views/pdf/employee-report.blade.php - Multi-page employee report Blade template
๐งช Testing Suite
- ๐ run-tests.php - Custom CLI test runner for fast local testing
- ๐งช tests/PdfGeneratorTest.php - Complete PHPUnit test suite
- ๐ข tests/basic-test.php - Basic integration test script
- ๐ก tests/advanced-test.php - Advanced features test script
- ๐ด tests/comprehensive-test.php - Comprehensive end-to-end test script
๐ค GitHub Templates (.github/)
- ๐ .github/PULL_REQUEST_TEMPLATE.md - Standard Pull Request template
- ๐ .github/ISSUE_TEMPLATE/bug_report.md - Issue template for bug reports
- ๐ก .github/ISSUE_TEMPLATE/feature_request.md - Issue template for feature requests
๐ Troubleshooting & Debugging
Common Issues & Solutions:
1. Memory Limit Exceeded
// Solution: Increase memory limit ini_set('memory_limit', '512M'); ini_set('max_execution_time', 300);
2. Font Not Found
// Solution: Use web-safe fonts or install custom fonts SimPdf::loadHtml($html) ->addStyle('body { font-family: Arial, sans-serif; }') ->download('document.pdf');
3. Images Not Displaying
// Solution: Use absolute URLs for images $html = '<img src="' . asset('images/logo.png') . '" alt="Logo">';
4. Page Breaks Not Working
// Solution: Use proper CSS classes $html = '<div class="page-break"></div>'; // Add CSS SimPdf::loadHtml($html) ->addStyle('.page-break { page-break-before: always; }') ->download('document.pdf');
5. Table Breaking Issues
// Solution: Configure table breaking SimPdf::loadHtml($html) ->breakTable([ 'repeat_header' => true, 'min_rows' => 5, 'max_rows' => 20 ]) ->download('document.pdf');
๐ง Debug Mode:
// Enable debug mode for troubleshooting SimPdf::loadHtml($html) ->setOptions([ 'debugPng' => true, 'debugKeepTemp' => true, 'debugCss' => true ]) ->download('document.pdf');
๐งช Running Tests
To run the complete test suite locally:
# Run integration test runner php run-tests.php # Run PHPUnit unit tests ./vendor/bin/phpunit tests/PdfGeneratorTest.php
๐ค Contributing
Contributions are welcome! Please check out our CONTRIBUTING.md and CODE_OF_CONDUCT.md for full guidelines.
Development Setup:
# Clone the repository git clone https://github.com/5u00n/sim-pdf-libs.git cd sim-pdf-libs # Install dependencies composer install # Run integration test runner php run-tests.php # Run PHPUnit unit tests ./vendor/bin/phpunit tests/PdfGeneratorTest.php
๐ License
This package is open-sourced software licensed under the MIT license.
Made with โค๏ธ for the Laravel community