Installation:
composer require dalv/wordbundle
Add to AppKernel.php:
new Dalv\WordBundle\DalvWordBundle(),
First Use Case: Generate a simple Word document with a single paragraph:
use Dalv\WordBundle\Service\WordService;
class DocumentController extends Controller
{
public function generateDocument()
{
$wordService = $this->get('dalv_word.word_service');
$phpWord = $wordService->createPHPWordObject();
$section = $phpWord->addSection();
$section->addText('Hello, Laravel!');
$writer = $wordService->createWriter($phpWord, 'Word2007');
$response = $wordService->createStreamedResponse($writer, 'document.docx');
return $response;
}
}
Key Entry Points:
dalv_word.word_service (Service ID) for core functionality.Dynamic Document Generation:
// Template-based approach
$templateProcessor = $wordService->getTemplateProcessor('template.docx');
$templateProcessor->setValue('{{name}}', $user->name);
$templateProcessor->saveAs('customized.docx');
Streaming Responses for Downloads:
// Force download with custom filename
$response = $wordService->createStreamedResponse(
$writer,
'invoice_' . $order->id . '.docx',
['Content-Type' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']
);
Multi-Page Documents:
$phpWord = $wordService->createPHPWordObject();
foreach ($reports as $report) {
$section = $phpWord->addSection();
$section->addText($report['title']);
$section->addTextBreak(1); // Page break
}
Integration with Forms:
// Generate a contract from form data
$contract = $this->generateContract($formData);
return $this->render('contracts/show.html.twig', [
'contract' => $contract,
]);
$phpWord once per request and reuse it for multiple operations.try {
$templateProcessor->saveAs($filePath);
} catch (\PhpOffice\PhpWord\Exception\ExceptionInterface $e) {
$this->addFlash('error', 'Failed to generate document: ' . $e->getMessage());
}
WordService into controllers/services instead of using $this->get().File Permissions:
www-data) has write permissions for output directories.sys_get_temp_dir()) for intermediate files.Memory Limits:
memory_limit. Increase it temporarily:
ini_set('memory_limit', '512M');
Template Processing Quirks:
{{name}}) are case-sensitive.Output Formats:
ODText or HTML formats if Word2007 output is inconsistent.Inspect Objects:
// Dump the PHPWord object structure (useful for debugging)
$section = $phpWord->getSections()[0];
var_dump($section->getElements());
Logging: Enable PHPWord’s logging for template processing:
$templateProcessor = $wordService->getTemplateProcessor('template.docx');
$templateProcessor->setLogger(new \Monolog\Logger('phpword'));
Common Errors:
'Word2007') matches the expected output.addSection() calls or empty text elements.Custom Styles:
$style = $phpWord->addStyle('custom', [
'fontSize' => 12,
'bold' => true,
'color' => 'FF0000',
]);
$section->addText('Highlighted', $style);
Images:
$section->addImage('path/to/image.jpg', [
'width' => 100,
'height' => 50,
'marginTop' => 10,
]);
Tables:
$table = $section->addTable(['borderSize' => 6, 'borderColor' => '000000']);
$table->addRow();
$table->addCell(2000)->addText('Header 1');
$table->addCell(2000)->addText('Header 2');
Event Listeners: Override the bundle’s service configuration to add custom logic:
# config/services.yaml
Dalv\WordBundle\Service\WordService:
arguments:
$customOption: '%kernel.project_dir%/config/word_templates'
Laravel-Specific Tips:
Storage facade for file handling:
use Illuminate\Support\Facades\Storage;
$path = Storage::disk('local')->path('documents/template.docx');
Response class for consistent headers:
return response()->streamDownload(
function () use ($writer) {
$writer->save('php://output');
},
'document.docx'
);
How can I help you explore Laravel packages today?