You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用unoconv转换docx为PDF时,PhpWord插入的图片不显示问题

PhpWord插入图片生成的Docx经unoconv转PDF后图片不显示的解决方法

问题场景

通过PhpOffice\PhpWord的TemplateProcessor类插入图片生成docx文件,使用unoconv转换为PDF后图片无法正常显示。

原插入图片代码

$document = new \PhpOffice\PhpWord1\TemplateProcessor($docx_temp_file_path);
$imagePath = '/abc.png';
if (file_exists($imagePath)) {
    $document->setImageValue($key, $imagePath);
}

原unoconv转换代码

public function docxToPdf( $docx_file_path, $pdf_file_path )
{
    $pythonPath = '/usr/bin/python';
    $unoconvPath = '/usr/bin/unoconv';
    $command = sprintf(
        '"%s" "%s" -f pdf "%s" 2>&1', 
        $pythonPath,
        $unoconvPath,
        $docx_file_path
    );

    exec($command, $output, $return);
    //
    if (is_array($output) && !empty($output[0])) {
        throw new Exception(json_encode(implode('; ', $output), true));
    }
    return true;
}

解决方案

1. 修正PhpWord图片嵌入逻辑

直接传入图片路径时,PhpWord可能仅引用图片而非嵌入文档,unoconv转换时无法读取外部引用资源。改用数组配置强制嵌入图片,并设置排版参数:

$document = new \PhpOffice\PhpWord1\TemplateProcessor($docx_temp_file_path);
$imagePath = '/abc.png';
if (file_exists($imagePath)) {
    $document->setImageValue($key, [
        'path' => $imagePath,
        'width' => 150, // 按需设置宽度
        'height' => 150, // 按需设置高度
        'ratio' => true, // 保持宽高比
        'isInline' => true // 设置为内联图片,避免排版异常
    ]);
}

2. 优化unoconv转换命令

原命令未指定输出路径,且参数处理存在风险,修改为明确指定输出路径并安全转义参数:

public function docxToPdf( $docx_file_path, $pdf_file_path )
{
    $pythonPath = '/usr/bin/python';
    $unoconvPath = '/usr/bin/unoconv';
    // 用-o指定输出路径,escapeshell系列函数处理特殊字符
    $command = sprintf(
        '%s %s -f pdf -o "%s" "%s" 2>&1', 
        escapeshellcmd($pythonPath),
        escapeshellcmd($unoconvPath),
        escapeshellarg($pdf_file_path),
        escapeshellarg($docx_file_path)
    );

    exec($command, $output, $return);
    
    // 基于返回值和输出内容判断转换是否失败
    if ($return !== 0 || (!empty($output) && strpos(implode(' ', $output), 'error') !== false)) {
        throw new Exception(implode('; ', $output));
    }
    return true;
}

3. 检查运行环境配置

  • LibreOffice版本:确保使用7.x及以上版本,旧版本对docx图片的兼容性较差。
  • 权限验证:运行PHP的用户(如www-data)需拥有图片、docx文件的读取权限,以及PDF输出目录的写入权限。
  • 命令行测试:直接在服务器执行unoconv -f pdf test.docx,确认转换后的PDF是否显示图片,排查unoconv本身的问题。

4. 验证生成的Docx文件

先手动打开生成的docx文件,确认图片能正常显示。若docx内图片已异常,需排查PhpWord的图片路径、文件完整性问题;若docx正常,则问题出在unoconv或LibreOffice配置。

内容的提问来源于stack exchange,提问作者user_777

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 01:38:20