PHPackages                             toporia/docura - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [PDF &amp; Document Generation](/categories/documents)
4. /
5. toporia/docura

ActiveLibrary[PDF &amp; Document Generation](/categories/documents)

toporia/docura
==============

High-performance document import/export package for Toporia Framework - PDF, Word, Excel, CSV, HTML

00PHP

Since Dec 17Pushed 5mo agoCompare

[ Source](https://github.com/Minhphung7820/toporia-docura)[ Packagist](https://packagist.org/packages/toporia/docura)[ RSS](/packages/toporia-docura/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

Toporia Docura
==============

[](#toporia-docura)

**High-Performance Document Import/Export Package for Toporia Framework**

[![PHP Version](https://camo.githubusercontent.com/6b84e9311750c972da98b6d521269a76c32b8928b672000d4a8c5dd7ac866d09/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d253345253344382e312d626c75652e737667)](https://www.php.net/)[![License](https://camo.githubusercontent.com/8bb50fd2278f18fc326bf71f6e88ca8f884f72f179d3e555e20ed30157190d0d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e2e737667)](LICENSE)

Docura provides a powerful, clean API for importing and exporting documents in various formats including PDF, Excel, Word, CSV, and HTML. Built with performance and memory efficiency in mind, it supports streaming for large datasets and provides a flexible template engine.

Features
--------

[](#features)

- **Multi-format Support**: PDF, Excel (xlsx/xls), Word (docx), CSV, HTML
- **Multiple PDF Drivers**: DomPDF, TCPDF, mPDF
- **High Performance**: Streaming and chunked processing for large files
- **Memory Efficient**: Generator-based lazy loading
- **Template Engine**: Simple yet powerful templating with loops, conditionals, and filters
- **Clean API**: Fluent interface with intuitive methods
- **ORM Integration**: Exportable/Importable traits for models
- **Queue Support**: Background processing for large exports
- **Zero Config**: Works out of the box with sensible defaults

Installation
------------

[](#installation)

```
composer require toporia/docura
```

### Optional Dependencies

[](#optional-dependencies)

Install based on your needs:

```
# For PDF export (choose one)
composer require dompdf/dompdf        # Recommended for simple HTML to PDF
composer require tecnickcom/tcpdf     # For complex layouts
composer require mpdf/mpdf            # For CJK characters and advanced features

# For Excel export/import
composer require phpoffice/phpspreadsheet

# For Word export/import
composer require phpoffice/phpword
```

Quick Start
-----------

[](#quick-start)

### Export Data

[](#export-data)

```
use function Toporia\Docura\docura;

// Export to Excel
$path = docura()->export($data, 'xlsx');

// Export to PDF
$path = docura()->export($data, 'pdf', ['title' => 'My Report']);

// Export to CSV
$path = docura()->export($data, 'csv');

// Export to Word
$path = docura()->export($data, 'docx');
```

### Download Export

[](#download-export)

```
// Direct download to browser
docura()->download($data, 'report.xlsx', 'xlsx');
docura()->download($data, 'invoice.pdf', 'pdf');
```

### Import Data

[](#import-data)

```
// Import from Excel
$data = docura()->import('path/to/file.xlsx');

// Import from CSV
$data = docura()->import('path/to/file.csv');

// Import with chunking for large files
foreach (docura()->importChunked('large-file.xlsx', null, 1000) as $chunk) {
    // Process 1000 rows at a time
    processChunk($chunk);
}

// Lazy import (one row at a time)
foreach (docura()->importLazy('huge-file.csv') as $row) {
    // Process each row
}
```

Helper Functions
----------------

[](#helper-functions)

```
// Export helpers
export_pdf($data, ['title' => 'Report']);
export_excel($data);
export_csv($data);
export_word($data);

// Import helpers
$data = import_excel('file.xlsx');
$data = import_csv('file.csv');

// Download helpers
download_pdf($data, 'report.pdf');
download_excel($data, 'data.xlsx');
download_csv($data, 'export.csv');
```

Specialized Exporters
---------------------

[](#specialized-exporters)

### PDF Export

[](#pdf-export)

```
$path = docura()->pdf()
    ->template('invoice')
    ->paper('A4', 'portrait')
    ->margins(10, 10, 10, 10)
    ->export($data);

// Using different drivers
$path = docura()->pdf()
    ->using('mpdf')  // or 'dompdf', 'tcpdf'
    ->export($data);
```

### Excel Export

[](#excel-export)

```
$path = docura()->excel()
    ->withHeaders(['Name', 'Email', 'Amount'])
    ->columnWidths([30, 50, 15])
    ->headerStyles(['bold' => true, 'background' => 'F0F0F0'])
    ->export($data);

// With row callback
$path = docura()->excel()
    ->eachRow(function ($row, $index) {
        $row['amount'] = '$' . number_format($row['amount'], 2);
        return $row;
    })
    ->export($data);

// Streaming for large datasets
$generator = function () {
    for ($i = 0; $i < 1000000; $i++) {
        yield ['id' => $i, 'name' => "Item {$i}"];
    }
};

$path = docura()->excel()->stream($generator(), 'large-export.xlsx');
```

### Word Export

[](#word-export)

```
$path = docura()->word()
    ->format('docx')  // or 'odt', 'rtf', 'html'
    ->export($data, [
        'title' => 'My Document',
        'description' => 'Generated by Docura',
    ]);
```

Template Engine
---------------

[](#template-engine)

Create templates in `resources/docura/templates/`:

```

>

    {{ title }}

        /* Your styles */

    {{ company.name }}
    Invoice #{{ invoice.number }}

                #
                Item
                Price

            @foreach items as item

                {{ loop.iteration }}
                {{ item.name }}
                {{ item.price|currency }}

            @endforeach

    @if notes

        Notes
        {{ notes }}

    @endif

        Generated on {{ date|datetime }}

```

Use the template:

```
$path = docura()->pdf()
    ->template('invoice')
    ->export([
        'title' => 'Invoice',
        'company' => ['name' => 'Acme Inc'],
        'invoice' => ['number' => 'INV-001'],
        'items' => [
            ['name' => 'Product A', 'price' => 99.99],
            ['name' => 'Product B', 'price' => 149.99],
        ],
        'notes' => 'Thank you for your business!',
        'date' => new DateTime(),
    ]);
```

### Template Features

[](#template-features)

**Variables:**

```
{{ variable }}
{{ object.property }}
{{ array.key }}
```

**Filters:**

```
{{ name|upper }}
{{ name|lower }}
{{ text|escape }}
{{ amount|currency }}
{{ amount|number }}
{{ date|date }}
{{ date|datetime }}
{{ html|nl2br }}
{{ items|count }}
```

**Loops:**

```
@foreach items as item
    {{ item.name }} - {{ loop.iteration }} of {{ loop.count }}
    @if loop.first
        (First item)
    @endif
@endforeach
```

**Conditionals:**

```
@if active
    Active
@elseif pending
    Pending
@else
    Inactive
@endif

@if count > 10
    Many items
@endif

@if !disabled
    Enabled
@endif
```

**Includes:**

```
@include('partials/header')
@include('partials/footer', ['year' => 2024])
```

ORM Integration
---------------

[](#orm-integration)

### Exportable Trait

[](#exportable-trait)

```
use Toporia\Docura\Concerns\Exportable;

class User extends Model
{
    use Exportable;

    protected static array $fillable = ['name', 'email', 'created_at'];
}

// Usage
$users = User::where('active', true)->get();
$path = $users->toExcel();
$users->downloadAsPdf('users.pdf');
```

### Importable Trait

[](#importable-trait)

```
use Toporia\Docura\Concerns\Importable;

class Product extends Model
{
    use Importable;

    protected static function getImportColumnMap(): array
    {
        return [
            'Product Name' => 'name',
            'SKU' => 'sku',
            'Price' => 'price',
        ];
    }
}

// Usage
$products = Product::importFromExcel('products.xlsx');

// With chunking for large files
Product::importChunked('huge-file.xlsx', 1000, function ($models, $total) {
    echo "Imported {$total} products so far\n";
});
```

Console Commands
----------------

[](#console-commands)

```
# Export data
php console docura:export data.json output.xlsx --format=xlsx
php console docura:export data.json output.pdf --format=pdf --title="My Report"

# Import data
php console docura:import file.xlsx --output=json
php console docura:import file.csv --output=table --limit=10

# Manage templates
php console docura:template create invoice --type=pdf
php console docura:template list
php console docura:template preview invoice --data='{"title":"Test"}'
```

Configuration
-------------

[](#configuration)

Publish the configuration:

```
php console vendor:publish --tag=docura-config
```

Configuration options (`config/docura.php`):

```
return [
    'pdf_driver' => env('DOCURA_PDF_DRIVER', 'dompdf'),
    'excel_driver' => env('DOCURA_EXCEL_DRIVER', 'phpspreadsheet'),

    'storage' => [
        'temp_path' => 'storage/docura/temp',
        'export_path' => 'storage/docura/exports',
        'import_path' => 'storage/docura/imports',
        'template_path' => 'resources/docura/templates',
    ],

    'pdf' => [
        'default_paper_size' => 'A4',
        'default_orientation' => 'portrait',
        'default_font' => 'DejaVu Sans',
        'enable_remote_images' => true,
    ],

    'excel' => [
        'default_format' => 'xlsx',
        'chunk_size' => 1000,
        'use_streaming' => true,
    ],

    'performance' => [
        'chunk_size' => 1000,
        'memory_limit' => '512M',
        'use_queue' => false,
    ],
];
```

Advanced Usage
--------------

[](#advanced-usage)

### Validation Before Import

[](#validation-before-import)

```
$errors = docura()->validateImport('file.xlsx', null, [
    'email' => 'required|email',
    'amount' => 'required|numeric|min:0',
]);

if (empty($errors)) {
    $data = docura()->import('file.xlsx');
}
```

### Process Each Row

[](#process-each-row)

```
docura()->each('large-file.csv', function ($row, $index) {
    // Process each row
    User::create($row);
}, 'csv');
```

### Get File Headers

[](#get-file-headers)

```
$headers = docura()->headers('file.xlsx');
// ['Name', 'Email', 'Phone', ...]
```

### Check Driver Availability

[](#check-driver-availability)

```
$drivers = docura()->getAvailableDrivers();
// ['dompdf' => true, 'tcpdf' => false, 'mpdf' => true, ...]

if (docura()->isDriverAvailable('mpdf')) {
    // Use mPDF
}
```

Performance Tips
----------------

[](#performance-tips)

1. **Use streaming for large exports**: Instead of loading all data into memory, use generators.
2. **Import in chunks**: Process large files in batches to avoid memory issues.
3. **Use native CSV driver**: For CSV files, the native driver is faster than PhpSpreadsheet.
4. **Enable caching**: Template caching reduces parsing overhead.
5. **Choose the right PDF driver**:

    - DomPDF: Simple HTML, fast
    - TCPDF: Complex layouts, Asian fonts
    - mPDF: Best CSS support, CJK characters

API Reference
-------------

[](#api-reference)

### DocuraManager

[](#docuramanager)

MethodDescription`export($data, $format, $options)`Export data to file`download($data, $filename, $format, $options)`Download export directly`store($data, $path, $format, $options)`Save export to specific path`stream($generator, $path, $format, $options)`Stream large exports`raw($data, $format, $options)`Get raw export content`import($path, $format, $options)`Import data from file`importChunked($path, $format, $chunkSize, $options)`Import in chunks`importLazy($path, $format, $options)`Import lazily (generator)`each($path, $callback, $format, $options)`Process each row`headers($path, $format, $options)`Get file headers`validateImport($path, $format, $rules, $options)`Validate before import`pdf()`Get PDF exporter`excel()`Get Excel exporter`csv()`Get CSV exporter`word()`Get Word exporter`template($name)`Set template for exportLicense
-------

[](#license)

MIT License. See [LICENSE](LICENSE) for details.

Credits
-------

[](#credits)

Developed by TMP DEV for the Toporia Framework.

###  Health Score

17

—

LowBetter than 6% of packages

Maintenance50

Moderate activity, may be stable

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity12

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/1cc240e87c451f2dd614b87bb0d07039e4a20d8b391221c651172cf341e0b6cd?d=identicon)[Minhphung7820](/maintainers/Minhphung7820)

---

Top Contributors

[![Minhphung7820](https://avatars.githubusercontent.com/u/110077842?v=4)](https://github.com/Minhphung7820 "Minhphung7820 (6 commits)")

### Embed Badge

![Health badge](/badges/toporia-docura/health.svg)

```
[![Health](https://phpackages.com/badges/toporia-docura/health.svg)](https://phpackages.com/packages/toporia-docura)
```

###  Alternatives

[phpoffice/phpspreadsheet

PHPSpreadsheet - Read, Create and Write Spreadsheet documents in PHP - Spreadsheet engine

13.9k293.5M1.3k](/packages/phpoffice-phpspreadsheet)[spatie/browsershot

Convert a webpage to an image or pdf using headless Chrome

5.2k32.1M102](/packages/spatie-browsershot)[smalot/pdfparser

Pdf parser library. Can read and extract information from pdf file.

2.7k34.5M216](/packages/smalot-pdfparser)[barryvdh/laravel-snappy

Snappy PDF/Image for Laravel

2.8k24.8M48](/packages/barryvdh-laravel-snappy)[openspout/openspout

PHP Library to read and write spreadsheet files (CSV, XLSX and ODS), in a fast and scalable way

1.1k57.6M131](/packages/openspout-openspout)[keboola/csv

Keboola CSV reader and writer

1451.8M21](/packages/keboola-csv)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
