You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

PHP导出含内网图片的Microsoft Word文档时图片不显示求助

解决Word导出后图片不显示的问题

我来帮你搞定这个问题~你遇到的核心问题是:Word文档里的图片是引用内网URL,当你下载后如果不在同一个内网环境,或者Word因为安全/解析问题无法访问这个内网地址,图片就加载不出来了。而且即使在同一内网,这种外部链接的方式也不太可靠,不如把图片直接嵌入到文档里。

解决方案:将图片转为Base64编码嵌入

把图片转换成Base64格式后直接写入HTML,这样图片数据会被包含在Word文档中,不需要依赖外部链接,无论在哪打开都能正常显示。

修改后的代码如下:

<?php
header('Content-type: application/x-msword');
header("Content-Disposition: attachment; filename=myfile.doc");

// 获取内网图片并转换为Base64编码
$imageUrl = 'http://192.168.100.97/i/xxx/header_surat_doc.jpg';

// 方式1:使用file_get_contents(需要服务器开启allow_url_fopen)
$imageData = file_get_contents($imageUrl);

// 方式2:如果allow_url_fopen关闭,用CURL替代(取消下面注释即可)
/*
$ch = curl_init($imageUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$imageData = curl_exec($ch);
curl_close($ch);
*/

$base64Image = base64_encode($imageData);
$imgSrc = 'data:image/jpeg;base64,' . $base64Image;
?>

<img src="<?php echo $imgSrc; ?>">
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the `1500s` when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.</p>

为什么这样有效?

Base64编码会把图片的二进制数据转换成纯文本格式,直接嵌入到HTML的img标签中。Word在解析这份HTML生成文档时,会自动把这段文本还原成图片,完全不需要再去请求外部的内网URL,自然就不会出现图片加载失败的问题了。

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

火山引擎 最新活动