Weave Code
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

Phpword Laravel Package

phpoffice/phpword

PHPWord is a pure-PHP library to create, read, and edit documents in DOCX (OOXML), ODT (ODF), RTF, HTML, and PDF. Build sections, headers/footers, styles, fonts, and document properties dynamically from your PHP apps.

View on GitHub
Deep Wiki
Context7
## Getting Started
### Minimal Setup
1. **Installation**:
   ```bash
   composer require phpoffice/phpword:^1.4.0

Verify the package loads by running:

composer show phpoffice/phpword
  1. First Use Case (Updated for 1.4.0): Create a basic Word document with a single paragraph and demonstrate new features like default font color:

    use PhpOffice\PhpWord\PhpWord;
    use PhpOffice\PhpWord\Settings;
    
    // Configure temp directory (critical for performance)
    Settings::setTemporaryFolder(sys_get_temp_dir());
    
    $phpWord = new PhpWord();
    
    // Set default font color (new in 1.4.0)
    $phpWord->setDefaultFontColor('FF0000'); // Red
    
    $section = $phpWord->addSection();
    $section->addText('Hello, PhpWord 1.4.0!');
    
    // Save to file
    $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
    $objWriter->save('hello.docx');
    
  2. Where to Look First:

    • Updated Official Documentation
    • PhpOffice\PhpWord\PhpWord class (core functionality)
    • PhpOffice\PhpWord\Element\ namespace (text, tables, images, etc.)
    • New features: Ruby text support, EPub3 writer, and improved table styling

Implementation Patterns

Core Workflows

Document Creation (Updated for 1.4.0)

// Initialize with default font settings (new in 1.4.0)
$phpWord = new PhpWord();
$phpWord->setDefaultFont('Arial');
$phpWord->setDefaultFontColor('0000FF'); // Blue
$phpWord->setDefaultFontSize(12);

// Add sections (required for content)
$section = $phpWord->addSection();

// Add content with new formatting options
$section->addText('Title', [
    'bold' => true,
    'size' => 16,
    'color' => 'FF0000' // Override default
]);

// Add ruby text (phonetic guide) - new in 1.4.0
$section->addRubyText('Ruby Text', 'Phonetic Guide');

// Save with improved writer options
$writer = IOFactory::createWriter($phpWord, 'Word2007');
$writer->save('output.docx');

Tables (Updated for 1.4.0)

$table = $section->addTable([
    'borderSize' => 6,
    'borderColor' => '0000FF',
    'cellMargin' => 5, // New padding support
    'cellPadding' => 10 // New padding support
]);

// Vertical alignment support (new in 1.4.0)
$table->addRow()->addCell(0)->addText('Header 1')->getCell(0, 0)->setValign('middle');
$table->addCell()->addText('Header 2')->getCell(0, 1)->setValign('top');

// Merged cells with improved styling
$table->addRow()->addCell(2)->addText('Merged Cell')->getCell(0, 0)->setColSpan(2);

Styles and Themes (Updated for 1.4.0)

// Define reusable styles with new options
$phpWord->addFontStyle('customBold', [
    'bold' => true,
    'size' => 12,
    'color' => '00FF00' // Green text
]);

$phpWord->addParagraphStyle('customStyle', [
    'alignment' => \PhpOffice\PhpWord\Shared\Converter::alignCenter,
    'indentFirstLine' => 0.5 // New firstLineChars support
]);

// Apply styles with new default font support
$section->addText('Styled Text', ['style' => 'customBold']);
$section->addText('Centered Paragraph', ['style' => 'customStyle']);

// Set default font for entire document (new in 1.4.0)
$phpWord->setDefaultFont('DejaVu Sans');

Headers/Footers (Updated for 1.4.0)

$header = $section->getHeader();
$header->addText('Page Header with Default Font');

// Improved TOC support (fixed in 1.4.0)
$phpWord->addTableOfContents('Table of Contents', 3);

Images (Updated for 1.4.0)

// Images in text runs (fixed in 1.4.0)
$textRun = $section->addTextRun();
$textRun->addText('Image in text: ');
$textRun->addImage('path/to/image.jpg', [
    'width' => 50,
    'height' => 50,
    'align' => 'middle'
]);

Integration Tips

  1. Laravel Service Provider (Updated for 1.4.0): Bind the package with new default font support:

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->bind(PhpWord::class, function () {
            $phpWord = new PhpWord();
            $phpWord->setDefaultFont('Arial');
            $phpWord->setDefaultFontColor('333333');
            return $phpWord;
        });
    }
    
  2. Queueable Jobs (Updated for 1.4.0): Offload document generation with improved memory handling:

    // app/Jobs/GenerateWordDocument.php
    public function handle()
    {
        $phpWord = new PhpWord();
        $phpWord->setDefaultFont('Calibri');
    
        // Use chunked saving for large files
        $writer = IOFactory::createWriter($phpWord, 'Word2007');
        $writer->save(storage_path('app/documents/large.docx'), [
            'chunkSize' => 2097152 // 2MB chunks
        ]);
    }
    
  3. Dynamic Content with Template Processor (Fixed in 1.4.0):

    $templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('template.docx');
    $templateProcessor->setValue('{{name}}', 'John Doe');
    
    // Fixed 0 vs empty string issue
    $templateProcessor->setValue('{{empty_field}}', ''); // Now works correctly
    
    $templateProcessor->saveAs('output.docx');
    
  4. New EPub3 Support (1.4.0):

    $writer = IOFactory::createWriter($phpWord, 'EPub3');
    $writer->save('output.epub');
    
  5. Ruby Text Support (New in 1.4.0):

    // For phonetic guides or annotations
    $section->addRubyText('主題', 'shǔtǐ'); // Chinese character with pinyin
    
  6. Improved HTML Integration:

    // Convert HTML to Word with improved table support
    $html = '<table><tr><td style="vertical-align: middle;">Centered</td></tr></table>';
    $phpWord = IOFactory::loadHTML($html);
    $writer = IOFactory::createWriter($phpWord, 'Word2007');
    $writer->save('html_to_word.docx');
    

Gotchas and Tips

Pitfalls

  1. Memory Limits (Updated):

    • Large documents (>50MB) may still hit PHP’s memory_limit. Use chunked saving:
      $writer->save('large.docx', ['chunkSize' => 1024 * 1024]); // 1MB chunks
      
    • New: EPub3 format may have different memory characteristics than DOCX.
  2. Temp Directory (Critical):

    • Always set a temporary folder:
      Settings::setTemporaryFolder(storage_path('app/temp'));
      
    • New: Consider using sys_get_temp_dir() with proper permissions for shared hosting.
  3. Font Substitution (Updated):

    • Custom fonts must still be registered, but 1.4.0 improves default font handling:
      $phpWord->addFont('DejaVuSans', ['fontFile' => 'path/to/DejaVuSans.ttf']);
      $phpWord->setDefaultFont('DejaVuSans');
      
  4. Table Cell Merging (Updated):

    • Use addCell() with addRow() carefully. Merged cells now support:
      $table->addRow()->addCell(2)->addText('Merged Cell')
            ->getCell(0, 0)->setColSpan(2)
      
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky