PHP code example of dskripchenko / laravel-php-docx

1. Go to this page and download the library: Download dskripchenko/laravel-php-docx library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

dskripchenko / laravel-php-docx example snippets


use Dskripchenko\LaravelPhpDocx\Facades\Docx;

// download a rendered Blade view as a Word document
Route::get('/contracts/{contract}', function (Contract $contract) {
    return Docx::view('contracts.show', ['contract' => $contract])
        ->download("contract-{$contract->number}.docx");
});

// header/footer views and a text watermark
Docx::view('contracts.show', $data,
    headerView: 'contracts.header',
    footerView: 'contracts.footer',
    watermark: 'DRAFT',
);

// views with <style> blocks / CSS classes (needs the suggested
// tijsverkoyen/css-to-inline-styles package)
Docx::view('contracts.styled', $data, inlineStyles: true);

$bytes = Docx::fromHtml('<h1>Report</h1><p>Body with <b>bold</b>.</p>')->bytes();

Docx::fromHtml($html)->save(storage_path('report.docx'));

// HTTP responses
return Docx::fromHtml($html)->download('report.docx');   // attachment
return Docx::fromHtml($html)->inline('report.docx');     // inline

// or via the response macro — accepts PendingDocx, Document, or bytes
return response()->docx(Docx::fromHtml($html), 'report.docx');

$imported = Docx::toHtml(file_get_contents('from-word.docx'));

$imported->bodyHtml;        // clean HTML with inline styles
$imported->headerHtml;      // header / footer as HTML
$imported->footerHtml;
$imported->watermarkText;

$variables = Docx::detectVariables($docxBytes);
// MERGEFIELD, SDT content controls, {{x}} / ${x} / %x% patterns

// substitute values while importing to HTML
$html = Docx::toHtml($docxBytes, ['customer_name' => 'ACME Corp'])->bodyHtml;

$document = Docx::builder()
    ->heading(1, 'Quarterly report')
    ->paragraph(fn ($p) => $p->text('Prepared for ')->bold('ACME Corp'))
    ->build();

return Docx::render($document)->download('report.docx');

return [
    'paper' => env('PHP_DOCX_PAPER', 'a4'),            // a3 | a4 | a5 | letter | legal
    'orientation' => env('PHP_DOCX_ORIENTATION', 'portrait'),
    'margins' => [                                      // millimetres; null = library default
        'top' => null, 'right' => null, 'bottom' => null, 'left' => null,
    ],
];
bash
composer 
bash
php artisan vendor:publish --tag=php-docx-config