Weave 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

Wordbundle Laravel Package

dalv/wordbundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require dalv/wordbundle
    

    Add to AppKernel.php:

    new Dalv\WordBundle\DalvWordBundle(),
    
  2. 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;
        }
    }
    
  3. Key Entry Points:

    • dalv_word.word_service (Service ID) for core functionality.
    • Refer to PHPWord Docs for API specifics.

Implementation Patterns

Common Workflows

  1. Dynamic Document Generation:

    // Template-based approach
    $templateProcessor = $wordService->getTemplateProcessor('template.docx');
    $templateProcessor->setValue('{{name}}', $user->name);
    $templateProcessor->saveAs('customized.docx');
    
  2. 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']
    );
    
  3. Multi-Page Documents:

    $phpWord = $wordService->createPHPWordObject();
    foreach ($reports as $report) {
        $section = $phpWord->addSection();
        $section->addText($report['title']);
        $section->addTextBreak(1); // Page break
    }
    
  4. Integration with Forms:

    // Generate a contract from form data
    $contract = $this->generateContract($formData);
    return $this->render('contracts/show.html.twig', [
        'contract' => $contract,
    ]);
    

Best Practices

  • Reuse Objects: Instantiate $phpWord once per request and reuse it for multiple operations.
  • Error Handling: Wrap operations in try-catch blocks for file I/O or template processing:
    try {
        $templateProcessor->saveAs($filePath);
    } catch (\PhpOffice\PhpWord\Exception\ExceptionInterface $e) {
        $this->addFlash('error', 'Failed to generate document: ' . $e->getMessage());
    }
    
  • Dependency Injection: Inject WordService into controllers/services instead of using $this->get().

Gotchas and Tips

Pitfalls

  1. File Permissions:

    • Ensure the web server user (e.g., www-data) has write permissions for output directories.
    • Use temporary directories (e.g., sys_get_temp_dir()) for intermediate files.
  2. Memory Limits:

    • Large documents may hit PHP’s memory_limit. Increase it temporarily:
      ini_set('memory_limit', '512M');
      
    • For very large files, consider chunked processing or streaming directly to the response.
  3. Template Processing Quirks:

    • Case Sensitivity: Template placeholders ({{name}}) are case-sensitive.
    • Nested Loops: Avoid deeply nested loops in templates; PHPWord may struggle with complex structures.
  4. Output Formats:

    • Not all formats support all features (e.g., PDF may not preserve complex tables or styles perfectly).
    • Test ODText or HTML formats if Word2007 output is inconsistent.

Debugging Tips

  1. Inspect Objects:

    // Dump the PHPWord object structure (useful for debugging)
    $section = $phpWord->getSections()[0];
    var_dump($section->getElements());
    
  2. Logging: Enable PHPWord’s logging for template processing:

    $templateProcessor = $wordService->getTemplateProcessor('template.docx');
    $templateProcessor->setLogger(new \Monolog\Logger('phpword'));
    
  3. Common Errors:

    • "File not found": Verify the template path is absolute or relative to the project root.
    • "Invalid format": Ensure the writer format (e.g., 'Word2007') matches the expected output.
    • Blank Output: Check for missing addSection() calls or empty text elements.

Extension Points

  1. Custom Styles:

    $style = $phpWord->addStyle('custom', [
        'fontSize' => 12,
        'bold' => true,
        'color' => 'FF0000',
    ]);
    $section->addText('Highlighted', $style);
    
  2. Images:

    $section->addImage('path/to/image.jpg', [
        'width' => 100,
        'height' => 50,
        'marginTop' => 10,
    ]);
    
  3. Tables:

    $table = $section->addTable(['borderSize' => 6, 'borderColor' => '000000']);
    $table->addRow();
    $table->addCell(2000)->addText('Header 1');
    $table->addCell(2000)->addText('Header 2');
    
  4. 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'
    
  5. Laravel-Specific Tips:

    • Use Laravel’s Storage facade for file handling:
      use Illuminate\Support\Facades\Storage;
      $path = Storage::disk('local')->path('documents/template.docx');
      
    • Integrate with Laravel’s Response class for consistent headers:
      return response()->streamDownload(
          function () use ($writer) {
              $writer->save('php://output');
          },
          'document.docx'
      );
      
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.
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus
elmogy/larafast