Deprecated: Optional parameter $keys declared before required parameter $cms_id is implicitly treated as a required parameter in /home/www/dev/work/class/blog/CmsKey.php on line 75

Deprecated: Creation of dynamic property lvesu\lvesu\controller\blog\main::$outlink is deprecated in /home/www/dev/work/website/lvesu/template/blog/cms/cms.tpl on line 2

Deprecated: Creation of dynamic property lvesu\lvesu\controller\blog\main::$status is deprecated in /home/www/dev/work/website/lvesu/template/blog/index.head.php on line 2
使用PHPWord将docx文件转换为html格式 - 互联网笔记

略微加速

略速 - 互联网笔记

使用PHPWord将docx文件转换为html格式

2025-05-19 leiting (18阅读)

标签 PHP

1.安装 PHPWord

composer require phpoffice/phpword

2.基础转换代码

require 'vendor/autoload.php';

use PhpOffice\PhpWord\IOFactory;

function convertDocxToHtml($inputFile, $outputFile) {
    // 读取 Word 文档
    $phpWord = IOFactory::load($inputFile);

    // 创建 HTML 写入器
    $htmlWriter = new \PhpOffice\PhpWord\Writer\HTML($phpWord);

    // 保存为 HTML 文件
    $htmlWriter->save($outputFile);
}

// 使用示例
convertDocxToHtml('input.docx', 'output.html');

高级处理(包含格式保留)

自定义样式转换

class CustomHtmlWriter extends \PhpOffice\PhpWord\Writer\HTML {
    public function writeStyles() {
        // 添加自定义 CSS
        $this->writeLn('<style>');
        $this->writeLn('body { font-family: Arial, sans-serif; }');
        $this->writeLn('h1 { color: #333; }');
        $this->writeLn('table { border-collapse: collapse; }');
        $this->writeLn('</style>');
    }
}

// 使用自定义写入器
$htmlWriter = new CustomHtmlWriter($phpWord);

处理图片

function convertDocxToHtmlWithImages($inputFile, $outputFile) {
    $phpWord = IOFactory::load($inputFile);

    // 创建临时图片目录
    $imagePath = 'images/';
    if (!file_exists($imagePath)) {
        mkdir($imagePath, 0777, true);
    }

    // 设置图片保存回调
    $htmlWriter = new \PhpOffice\PhpWord\Writer\HTML($phpWord);
    $htmlWriter->setImageUriCallback(function ($source) use ($imagePath) {
        $filename = basename($source);
        copy($source, $imagePath.$filename);
        return $imagePath.$filename;
    });

    $htmlWriter->save($outputFile);
}

完整示例(包含表格/列表)

function advancedDocxToHtml($inputFile) {
    $phpWord = IOFactory::load($inputFile);
    $html = '';

    foreach ($phpWord->getSections() as $section) {
        // 处理页眉
        $header = $section->getHeader();
        if ($header) {
            $html .= '<header>'.$header->getText().'</header>';
        }

        // 处理正文元素
        foreach ($section->getElements() as $element) {
            if ($element instanceof \PhpOffice\PhpWord\Element\TextRun) {
                $html .= '<p>';
                foreach ($element->getElements() as $text) {
                    $style = [];
                    $text->getFontStyle() && $text->getFontStyle()->getBold() && $style[] = 'font-weight:bold';
                    $text->getFontStyle() && $text->getFontStyle()->getItalic() && $style[] = 'font-style:italic';
                    $html .= sprintf('<span style="%s">%s</span>',
                        implode(';', $style),
                        nl2br($text->getText())
                    );
                }
                $html .= '</p>';
            } elseif ($element instanceof \PhpOffice\PhpWord\Element\Table) {
                $html .= '<table border="1">';
                foreach ($element->getRows() as $row) {
                    $html .= '<tr>';
                    foreach ($row->getCells() as $cell) {
                        $html .= '<td>'.$cell->getText().'</td>';
                    }
                    $html .= '</tr>';
                }
                $html .= '</table>';
            }
        }
    }
    return $html;
}

// 输出结果
echo advancedDocxToHtml('document.docx');

注意事项

  1. 格式限制

    • 复杂样式(渐变填充/艺术字等)无法完全保留

    • 建议在转换后手动调整CSS样式

  2. 性能优化

    • 大文件处理建议分块读取

    • 启用缓存机制:

      \PhpOffice\PhpWord\Settings::setTempDir(sys_get_temp_dir());
  3. 编码问题

    • 中文文档需指定编码:

      $html = '<meta charset="UTF-8">'.$html;
  4. 扩展功能

    • 使用 Dompdf 可将HTML转换为PDF:

      composer require dompdf/dompdf
      
      $dompdf->loadHtml($html);
      $dompdf->render();

推荐工作流程

  1. 上传 .docx 文件到服务器

  2. 使用 PHPWord 转换为基础HTML

  3. 通过正则表达式清理冗余标签

  4. 添加自定义CSS样式

  5. 输出到浏览器或保存为静态文件

此方案可处理大部分常规文档转换需求,对于复杂格式建议结合前端编辑器(如 CKEditor)进行二次优化。


北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3