Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Rtf Laravel Package

jstewmc/rtf

PHP library for reading, parsing, and working with Rich Text Format (RTF) documents. Extract text and metadata, traverse document structure, and integrate RTF handling into your applications with a lightweight, dependency-friendly package.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require jstewmc/rtf
    

    Requires PHP 7.4+ and the ext-dom extension.

  2. First Use Case: Reading RTF

    use JSTewMc\RTF\RTF;
    
    $rtf = RTF::loadFromFile('document.rtf');
    echo $rtf->getText(); // Extract plain text
    
  3. First Use Case: Writing RTF

    $rtf = new RTF();
    $rtf->addText('Hello, RTF!');
    $rtf->saveToFile('output.rtf');
    
  4. Key Entry Points

    • RTF::loadFromFile() / RTF::loadFromString() for parsing.
    • $rtf->getText() for plain-text extraction.
    • $rtf->addText(), $rtf->addImage(), etc., for building documents.
    • $rtf->saveToFile() / $rtf->saveToString() for output.
  5. Documentation

    • GitHub README (if available).
    • Method signatures in IDE autocompletion (limited but functional).

Implementation Patterns

Common Workflows

1. Extracting Data from RTF

$rtf = RTF::loadFromFile('invoices.rtf');
$text = $rtf->getText(); // Full plain-text content
$images = $rtf->getImages(); // Array of embedded images (base64)

Use Case: Scraping structured data (e.g., invoices, reports) where RTF is the source.

2. Generating RTF Reports

$rtf = new RTF();
$rtf->addText('Invoice #12345', ['font' => 'Arial', 'size' => 14, 'bold' => true]);
$rtf->addParagraph('Date: ' . now()->format('Y-m-d'));
$rtf->addTable([
    ['Item', 'Qty', 'Price'],
    ['Product A', 2, '$10.00'],
]);
$rtf->saveToFile('invoice.rtf');

Use Case: Dynamic report generation (e.g., PDF alternatives, Word-like exports).

3. Modifying Existing RTF

$rtf = RTF::loadFromFile('template.rtf');
$rtf->replaceText('{name}', 'John Doe'); // Simple string replacement
$rtf->saveToFile('personalized.rtf');

Use Case: Templating (e.g., merging RTF templates with user data).

4. Handling Images

$rtf = new RTF();
$rtf->addImage('logo.png', 'Logo', ['width' => 200, 'height' => 100]);
$rtf->saveToFile('document.rtf');

Use Case: Embedding logos, charts, or signatures in generated documents.


Integration Tips

Laravel-Specific

  • Store RTF in Database: Use saveToString() to store RTF as a text column, then loadFromString() to retrieve.

    $rtfString = $rtf->saveToString();
    $model->document = $rtfString;
    $model->save();
    
  • Queue RTF Generation: Dispatch a job for heavy RTF processing (e.g., large tables or images).

    GenerateRtfJob::dispatch($data)->onQueue('rtf');
    
  • Blade Templating: Combine with Blade for dynamic content:

    $rtf = new RTF();
    $rtf->addText(view('emails.rtf_template', ['user' => $user])->render());
    

Performance

  • Batch Processing: For large files, process in chunks or use streaming where possible.
  • Caching: Cache parsed RTF objects if regenerating frequently.

Testing

  • Unit Tests: Mock RTF class to test interactions with RTF-generated content.
  • Golden Master Tests: Compare generated RTF against a known-good baseline (e.g., using files_equal()).

Gotchas and Tips

Pitfalls

1. RTF Complexity

  • Issue: RTF is a verbose format with many edge cases (e.g., nested tables, custom styles).
  • Fix: Start with simple documents (text/basic formatting) before tackling complex layouts.
  • Workaround: Use getText() for plain-text extraction if full parsing fails.

2. Image Handling

  • Issue: Embedded images may not render correctly if:
    • The image format isn’t supported (e.g., SVG).
    • The base64 encoding is corrupted.
  • Fix: Validate images before embedding:
    if (!getimagesizefromstring(file_get_contents('image.png'))) {
        throw new \InvalidArgumentException('Invalid image');
    }
    

3. Encoding/Unicode

  • Issue: RTF may mishandle non-ASCII characters (e.g., emojis, Cyrillic).
  • Fix: Explicitly set encoding when adding text:
    $rtf->addText('Привет!', ['encoding' => 'utf-8']);
    

4. Memory Limits

  • Issue: Large RTF files (e.g., 100MB+) may hit PHP’s memory_limit.
  • Fix: Increase memory_limit or process files in chunks.

5. Table Limitations

  • Issue: Nested tables or merged cells may not render as expected.
  • Fix: Use simple tables first; test with tools like LibreOffice for validation.

Debugging Tips

1. Inspect Raw RTF

$rtfString = $rtf->saveToString();
file_put_contents('debug.rtf', $rtfString);

Open debug.rtf in a text editor to verify structure.

2. Validate with External Tools

3. Logging

try {
    $rtf->addText('Test'); // May throw exceptions
} catch (\Exception $e) {
    \Log::error('RTF generation failed', ['error' => $e->getMessage(), 'trace' => $e->getTraceAsString()]);
}

Extension Points

1. Custom Styles

Extend the package by adding custom style handlers:

$rtf->addText('Custom Style', [
    'font' => 'CustomFont',
    'size' => 12,
    'color' => '\red255\green0\blue0\' // RGB in RTF syntax
]);

2. Plugins/System

  • Laravel Service Provider: Bind the RTF class for dependency injection:
    $this->app->bind(RTF::class, function () {
        return new RTF();
    });
    
  • Artisan Commands: Create commands for bulk RTF processing:
    php artisan rtf:generate --file=template.rtf --data=user1.json
    

3. Event Listeners

Trigger events for RTF generation (e.g., logging, notifications):

event(new RtfGenerated($rtf, 'document.rtf'));

4. Forking the Package

  • Why: Add missing features (e.g., footnotes, headers).
  • How: Clone the repo, extend the RTF class, and publish as a private package.

Config Quirks

  • No Built-in Config: The package is lightweight with no .env or config file. All options are method arguments.
  • Default Styles: Use the package’s defaults for simplicity, but override as needed:
    $rtf->setDefaultFont('Arial');
    $rtf->setDefaultSize(12);
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed