PHPackages                             agungsugiarto/latex-for-laravel - 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. [Templating &amp; Views](/categories/templating)
4. /
5. agungsugiarto/latex-for-laravel

ActiveLibrary[Templating &amp; Views](/categories/templating)

agungsugiarto/latex-for-laravel
===============================

A Laravel package that provides seamless integration between Laravel Blade templates and LaTeX, enabling dynamic PDF generation

v1.0.2(1y ago)111[4 PRs](https://github.com/agungsugiarto/latex-for-laravel/pulls)MITPHPPHP ^8.1CI passing

Since Jun 28Pushed 2mo agoCompare

[ Source](https://github.com/agungsugiarto/latex-for-laravel)[ Packagist](https://packagist.org/packages/agungsugiarto/latex-for-laravel)[ Docs](https://github.com/agungsugiarto/latex-for-laravel)[ GitHub Sponsors](https://github.com/agungsugiarto)[ RSS](/packages/agungsugiarto-latex-for-laravel/feed)WikiDiscussions main Synced today

READMEChangelog (3)Dependencies (11)Versions (10)Used By (0)

LaTeX for Laravel
=================

[](#latex-for-laravel)

[![Latest Version on Packagist](https://camo.githubusercontent.com/4c2048c46f94df3d0922e414e7554a0b9e0824728057bb37b408c5b72e734192/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6167756e67737567696172746f2f6c617465782d666f722d6c61726176656c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/agungsugiarto/latex-for-laravel)[![GitHub Tests Action Status](https://camo.githubusercontent.com/4882c19edce74d8f57dce020804280458ef8425eb84939797407bc06e17748d3/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6167756e67737567696172746f2f6c617465782d666f722d6c61726176656c2f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/agungsugiarto/latex-for-laravel/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/7c486645693ef3556a817b1a6c801158f2fd78f99d390c004592a0e2b4e072ee/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6167756e67737567696172746f2f6c617465782d666f722d6c61726176656c2f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/agungsugiarto/latex-for-laravel/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/2973f738e68bcd48bfef659cbc63088cc251d50069d9b52451fb4567cc6af565/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6167756e67737567696172746f2f6c617465782d666f722d6c61726176656c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/agungsugiarto/latex-for-laravel)

A Laravel package that provides seamless integration between Laravel Blade templates and LaTeX, enabling you to create dynamic PDF documents using familiar Blade syntax while maintaining valid LaTeX structure.

Features
--------

[](#features)

- 🔥 **Blade + LaTeX Integration**: Use Laravel Blade directives within LaTeX templates
- 📄 **Valid LaTeX Structure**: Templates remain compilable with standard LaTeX compilers
- 🎯 **Multiple Output Formats**: Generate PDFs, download source files, or return content as strings
- 🚀 **Easy to Use**: Simple API with powerful customization options
- ⚡ **Pipeline-Based Processing**: Clean, extensible compilation using Laravel Pipeline
- 🔌 **Extensible**: Add custom processors and restorers for specialized LaTeX needs
- 🧪 **Well Tested**: Comprehensive test suite ensuring reliability

Support us
----------

[](#support-us)

[![Support via Saweria](https://camo.githubusercontent.com/3b2c914ff67a5c7901fdabb15957f68f331428fdf7f9949542cc5bb0bc0677da/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f537570706f72742d536177657269612d6f72616e67653f7374796c653d666c61742d737175617265)](https://saweria.co/agungsugiarto)

If this package helps you in your projects, consider supporting the development by [buying me a coffee on Saweria](https://saweria.co/agungsugiarto).

Your support helps maintain and improve this package for the Laravel community. ☕️

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

[](#installation)

You can install the package via composer:

```
composer require agungsugiarto/latex-for-laravel
```

The package will automatically register its service provider.

Requirements
------------

[](#requirements)

- PHP 8.1 or higher
- Laravel 10.0 or higher
- `pdflatex` installed on your system (for PDF compilation)

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

[](#quick-start)

Create a LaTeX template file `resources/views/invoice.blade.tex`:

```
\documentclass{article}
\usepackage[utf8]{inputenc}
\newcommand{\blade}[1]{}
\begin{document}

\title{\blade{{ $title }}}
\author{\blade{{ $author }}}
\maketitle

\blade{@foreach($items as $item)}
\section{\blade{{ $item['name'] }}}
\blade{{ $item['description'] }}
\blade{@endforeach}

\end{document}
```

Use it in your controller:

```
// Generate and download PDF
return view('invoice', [
    'title' => 'Monthly Invoice',
    'author' => 'John Doe',
    'items' => [
        ['name' => 'Service 1', 'description' => 'Description here'],
        ['name' => 'Service 2', 'description' => 'Another description'],
    ]
])->compile('invoice.pdf', 'download');
```

LaTeX Template Structure
------------------------

[](#latex-template-structure)

All `.blade.tex` files must follow this structure to ensure they are valid LaTeX documents that can be compiled directly while still supporting Laravel Blade directives.

### Required Structure

[](#required-structure)

#### 1. Include the `\newcommand{\blade}[1]{}` definition

[](#1-include-the-newcommandblade1-definition)

Every LaTeX template must include this command in the preamble:

```
\documentclass{article}
\usepackage[utf8]{inputenc}
\newcommand{\blade}[1]{}
\begin{document}
% Your content here
\end{document}
```

#### 2. Wrap all Blade directives in `\blade{}`

[](#2-wrap-all-blade-directives-in-blade)

All PHP/Blade code must be wrapped in `\blade{}` commands. There are three forms of blade directives:

##### Escaped Output: `\blade{{ expression }}`

[](#escaped-output-blade-expression-)

For safe output of variables that should be escaped to prevent LaTeX compilation issues:

```
% Variable output
\title{\blade{{ $title }}}
\author{\blade{{ $author->name }}}

% Method calls and complex expressions
\section{\blade{{ $document->getFormattedTitle() }}}
\date{\blade{{ now()->format('Y-m-d') }}}
```

##### Unescaped Output: `\blade{!! expression !!}`

[](#unescaped-output-blade-expression-)

For raw LaTeX content that should be rendered without escaping:

```
% Raw LaTeX commands
\blade{!! $latexCommands !!}

% Pre-formatted LaTeX content
\blade{!! '\textbf{Bold} and \textit{italic} text' !!}

% Complex LaTeX structures
\blade{!! $generatedTableContent !!}
```

##### Literal Content: `\blade{content}`

[](#literal-content-bladecontent)

For Blade directives, PHP code, and other content that should pass through directly:

```
% Control structures
\blade{@if($condition)}
\section{Conditional Section}
\blade{@endif}

\blade{@foreach($items as $item)}
\item \blade{{ $item['name'] }}: \blade{{ $item['description'] }}
\blade{@endforeach}

% PHP code blocks
\blade{@php
    $processedData = processData($rawData);
    $formattedOutput = formatForLaTeX($processedData);
@endphp}

% Blade components and includes
\blade{@include('partials.latex-header')}
\blade{@yield('content')}
```

### Complete Example

[](#complete-example)

```
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{graphicx}
\newcommand{\blade}[1]{}

\begin{document}

\title{\blade{{ $title }}}
\author{\blade{{ $author }}}
\date{\blade{{ $date }}}
\maketitle

\tableofcontents

\blade{@foreach($sections as $section)}
\section{\blade{{ $section['title'] }}}
\blade{{ $section['content'] }}

\blade{@if(isset($section['subsections']))}
\blade{@foreach($section['subsections'] as $subsection)}
\subsection{\blade{{ $subsection['title'] }}}
\blade{!! $subsection['content'] !!}
\blade{@endforeach}
\blade{@endif}

\blade{@endforeach}

\blade{@if($includeReferences)}
\bibliography{\blade{{ $bibliographyFile }}}
\blade{@endif}

\end{document}
```

### Benefits of This Structure

[](#benefits-of-this-structure)

1. **Valid LaTeX**: The file can be compiled directly with `pdflatex` without processing Blade directives
2. **Blade Processing**: Laravel can process all `\blade{}` commands to generate dynamic content
3. **IDE Support**: LaTeX editors will recognize the file as valid LaTeX and provide syntax highlighting
4. **Version Control**: The files are readable and diffable in version control systems

Pipeline Processing Architecture
--------------------------------

[](#pipeline-processing-architecture)

The package uses a modern pipeline-based approach for processing LaTeX templates, providing clean separation of concerns and extensibility for custom use cases.

### How It Works

[](#how-it-works)

The compilation process follows these steps:

1. **Blade Directive Processing**: Using Laravel Pipeline, the compiler processes different types of `\blade{}` directives:

    - `\blade{!! raw content !!}` → Direct unescaped output
    - `\blade{{ expression }}` → Escaped output (converted to markers, then restored as PHP echo statements)
    - `\blade{literal content}` → Direct literal content (for Blade directives, PHP code, etc.)
2. **Blade Compilation**: Standard Laravel Blade compilation processes the resulting template
3. **Marker Restoration**: Another pipeline restores any temporary markers to proper PHP code

### Built-in Processors

[](#built-in-processors)

#### Raw Content Processor

[](#raw-content-processor)

Handles unescaped LaTeX content:

```
\blade{!! $latexCommands !!}      % → {!! $latexCommands !!}
\blade{!! '\textbf{Bold Text}' !!} % → {!! '\textbf{Bold Text}' !!}
```

#### Echo Expression Processor

[](#echo-expression-processor)

Handles escaped variable output:

```
\blade{{ $documentTitle }}         % →
\blade{{ $author->name }}          % →
\blade{{ config('latex.class') }}  % →
```

#### Literal Content Processor

[](#literal-content-processor)

Handles Blade directives and PHP code:

```
\blade{@if($condition)}            % → @if($condition)
\blade{@foreach($items as $item)}  % → @foreach($items as $item)
\blade{}        % →
\blade{@yield('content')}          % → @yield('content')
```

### Extending the Pipeline

[](#extending-the-pipeline)

You can add custom processors and restorers to handle specialized LaTeX needs:

#### Adding Custom Processors

[](#adding-custom-processors)

```
// Get the compiler instance using the service container binding
$compiler = app('latex.compiler');

// Add a custom processor for mathematical expressions
$compiler->addProcessor(function($content, $next) {
    // Process custom \math{} directives
    $content = preg_replace(
        '/\\\\math\s*{(.*?)}/s',
        '\\begin{equation}$1\\end{equation}',
        $content
    );

    return $next($content);
});

// Add a processor for custom bibliography handling
$compiler->addProcessor(function($content, $next) {
    // Process \bibref{} to \cite{}
    $content = str_replace('\bibref{', '\cite{', $content);

    return $next($content);
});
```

#### Adding Custom Restorers

[](#adding-custom-restorers)

```
// Get the compiler instance using the service container binding
$compiler = app('latex.compiler');

// Add a custom restorer for special markers
$compiler->addRestorer(function($content, $next) {
    // Restore custom markers to PHP code
    $content = preg_replace(
        '/###CUSTOM_MATH_START###(.*?)###CUSTOM_MATH_END###/',
        '',
        $content
    );

    return $next($content);
});
```

#### Complete Custom Extension Example

[](#complete-custom-extension-example)

```
