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

WordPress插件中Dompdf生成PDF图片不显示的解决求助

解决Dompdf生成PDF时图片不显示(image not found or type unknown)的问题

针对你在WordPress插件中使用Dompdf转HTML到PDF时遇到的图片加载失败问题,提供以下几种可行解决方案:

1. 动态生成正确的图片路径,避免硬编码

不要直接写固定的物理路径,利用WordPress内置函数获取插件目录的URL或路径,确保路径在不同环境下都有效:
在doc.php中修改图片引用:

<?php
// 获取插件目录的绝对URL
$logo_url = plugin_dir_url(__FILE__) . 'logo.png';
?>
<img src="<?php echo esc_url($logo_url); ?>">

2. 配置Dompdf的访问权限选项

Dompdf默认可能限制本地文件访问,通过设置选项允许远程/本地文件访问,并指定根目录:
修改你的核心PHP代码:

require 'vendor/autoload.php';
use Dompdf\Dompdf;
use Dompdf\Options;

$options = new Options();
// 允许访问本地文件和远程URL
$options->set('isRemoteEnabled', true);
// 设置Dompdf可访问的根目录为WordPress站点根目录
$options->set('chroot', ABSPATH);

ob_start();
include plugin_dir_path(__FILE__) . 'doc.php';
$html = ob_get_clean();

$dompdf = new Dompdf($options);
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();

$outputPath = plugin_dir_path(__FILE__) . 'order_' . $order_id . '_suffix.pdf';
$output = $dompdf->output();
file_put_contents($outputPath, $output);

3. 验证图片文件权限

确保logo.png文件的权限设置正确,服务器进程(如www-data)需要有读取权限:

  • 文件权限设置为644
  • 文件所在目录权限设置为755

4. 嵌入Base64编码的图片(终极方案)

如果路径和权限问题无法解决,可以将图片转为Base64编码直接嵌入HTML,彻底避免文件路径依赖:
在doc.php中修改:

<?php
$logo_path = plugin_dir_path(__FILE__) . 'logo.png';
// 读取图片并转为Base64
if (file_exists($logo_path)) {
    $logo_base64 = 'data:image/png;base64,' . base64_encode(file_get_contents($logo_path));
} else {
    $logo_base64 = ''; // 处理文件不存在的情况
}
?>
<img src="<?php echo $logo_base64; ?>" alt="Logo">

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 07:10:16