FPDF生成PDF时头部图片不显示问题求助
解决FPDF头部图片无法显示的问题
我之前也碰到过类似的情况!你的代码逻辑本身没问题,但Google Charts的远程图片加载在FPDF里容易踩几个小坑,咱们来一步步解决:
可能的原因及解决方案
1. 远程URL的重定向或访问限制
Google Charts的链接有时候会触发重定向,而FPDF的Image()方法默认不会自动处理重定向请求。最稳妥的办法是先把图表图片下载到本地,再引用本地文件路径:
// 替换成你本地保存的图片路径 $this->Image('chart.png',60,30,90,0,'PNG');
2. 服务器禁用了远程资源加载
如果你的PHP环境中allow_url_fopen被设为Off,file_get_contents和FPDF的远程图片加载都会失效。可以手动获取图片内容再传入FPDF:
function Header(){ $chartUrl = 'http://chart.googleapis.com/chart?cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World'; // 获取远程图片内容 $chartContent = file_get_contents($chartUrl); if($chartContent){ // 创建临时文件存储图片 $tempFile = tempnam(sys_get_temp_dir(), 'fpdf_chart'); file_put_contents($tempFile, $chartContent); // 加载临时文件到PDF $this->Image($tempFile,60,30,90,0,'PNG'); // 用完删除临时文件 unlink($tempFile); } else { // 加载失败时显示提示 $this->SetFont('Arial','B',12); $this->Cell(0,10,'Chart unavailable',0,1,'C'); } $this->Ln(20); }
3. 图片尺寸参数不匹配
你指定的宽度90可能和图片实际尺寸不兼容,可以尝试去掉宽度参数,让FPDF自动识别:
$this->Image('http://chart.googleapis.com/chart?cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World',60,30,0,0,'PNG');
完整修改后的代码示例
class PDF extends FPDF{ function Header(){ // 优先使用本地图片(更稳定) $localChart = 'chart.png'; if(file_exists($localChart)){ $this->Image($localChart,60,30,90,0,'PNG'); } else { // fallback到远程加载 $chartUrl = 'http://chart.googleapis.com/chart?cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World'; $chartContent = file_get_contents($chartUrl); if($chartContent){ $tempFile = tempnam(sys_get_temp_dir(), 'fpdf_chart'); file_put_contents($tempFile, $chartContent); $this->Image($tempFile,60,30,90,0,'PNG'); unlink($tempFile); } else { $this->SetFont('Arial','B',12); $this->Cell(0,10,'Chart failed to load',0,1,'C'); } } $this->Ln(20); } function Footer() { $this->SetY(-15); $this->SetFont('Arial','I',8); $this->Cell(0,10,'Page '.$this->PageNo().'/{nb}',0,0,'C'); } } $pdf = new PDF(); $pdf->AliasNbPages(); $pdf->AddPage(); // 后续内容...
内容的提问来源于stack exchange,提问作者gpap13
相关产品推荐
相关产品推荐

