如何在Dompdf 3.0.0中添加PDF背景图片(CodeIgniter3场景)
解决Dompdf 3.0.0生成PDF时背景图片缺失的问题
你的代码存在三个核心问题导致背景图无法加载:
- CSS中
background-image未使用url()函数包裹路径,属于语法错误; - 直接在静态HTML字符串中调用CodeIgniter的
base_url()函数无效,PHP代码不会被解析; setBasePath的使用逻辑与CSS中的路径不匹配。
以下是两种可靠的修正方案:
方案一:使用本地绝对文件路径(推荐)
直接传入图片的绝对文件路径给Dompdf,避免路径解析问题:
public function index() { // 加载Dompdf库 $dompdf = new Dompdf\Dompdf(); // 获取图片绝对路径,处理跨系统路径分隔符 $imagePath = realpath(FCPATH . 'uploads/background_images/CoverImage1.jpg'); $imageUrl = 'file://' . str_replace(DIRECTORY_SEPARATOR, '/', $imagePath); // 修正后的HTML内容 $html = ' <html> <head> <style> body { background-image: url("'.$imageUrl.'"); background-repeat: no-repeat; /* 可选:取消图片重复 */ background-size: cover; /* 可选:让图片覆盖整个页面 */ background-position: center; /* 可选:居中显示图片 */ } </style> </head> <body> <h2>Background Image</h2> <p style="color:red">By default, the background image will repeat itself if it is smaller than the element where it is specified, in this case the body element.</p> </body> </html> '; $dompdf->loadHtml($html); $dompdf->render(); $dompdf->stream("hello_world.pdf", array("Attachment" => false)); }
方案二:使用setBasePath配合相对路径
设置基础路径后,CSS中仅使用图片文件名作为相对路径:
public function index() { // 加载Dompdf库 $dompdf = new Dompdf\Dompdf(); // 设置基础路径为图片所在目录 $basePath = realpath(FCPATH . 'uploads/background_images/'); $dompdf->setBasePath($basePath); // 修正后的HTML内容 $html = ' <html> <head> <style> body { background-image: url("CoverImage1.jpg"); background-repeat: no-repeat; background-size: cover; background-position: center; } </style> </head> <body> <h2>Background Image</h2> <p style="color:red">By default, the background image will repeat itself if it is smaller than the element where it is specified, in this case the body element.</p> </body> </html> '; $dompdf->loadHtml($html); $dompdf->render(); $dompdf->stream("hello_world.pdf", array("Attachment" => false)); }
额外注意事项
- 确保图片文件存在,且Web服务器用户(如www-data)拥有该文件的读取权限;
- Dompdf 3.0.0对资源路径解析更严格,本地文件优先使用绝对路径或基于
setBasePath的相对路径,避免使用URL形式; - 可通过
background-size、background-position等属性优化背景图的显示效果。
内容的提问来源于stack exchange,提问作者Solmaz
相关产品推荐
相关产品推荐

