我正在使用和DOMPDF库。当我用内联css测试它时,一切都很完美。但是,当我试图将css代码移动到外部文件时,不会将规则应用到html页面。
这是我的密码。
require_once("DomPdf/dompdf_config.inc.php");
$this->_helper->layout->disableLayout();
$html = $this->view->render('index/dom.phtml');
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
$pdfContent = $dompdf->output();
file_put_contents('sample.pdf', $pdfContent);
die("test");
2.相应视图的代码(index/dom.phtml)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link type="text/css" href="/themes/css/pdf.css" rel="stylesheet" media="screen"/>
</head>
<body>
<div>Tamara testing</div>
<table border="1">
<tr>
<th>Column 1</th>
<th>Column 2</th>
</tr>
<tr>
<td>Value 1</td>
<td>Value 2</td>
</tr>
</table>
</body>
</html>
3.我的css文件:
div {color: red;}
怎么让它起作用?
更新:
为了使它发挥作用,我更改了以下内容:
1.在控制器的操作中添加外部文件的基本路径
$dompdf->set_base_path(APPLICATION_PATH."/../public/themes/css/");
2.考虑到更改链接标签的href属性。使其相对于步骤1中的基本路径设置。
<link type="text/css" href="pdf.css" rel="stylesheet" />
发布于 2013-06-19 08:20:53
这实际上与无关,但是您需要提供正确的路径来从DomPDF加载“外部”文件。
$dompdf = new DOMPDF();
$dompdf->setBasePath(realpath(APPLICATION_PATH . '/path/to/css/'));
$dompdf->loadHtml($html);
$dompdf->render();
有关此特性,请参见手册 of DomPDF。
发布于 2014-10-19 21:46:50
@Jurian Sluiman走在正确的轨道上,但不幸的是,他的回答并没有帮助我。
为了找到对我有用的解决方案,我不得不花一些时间,那就是使用DOMPDF::set_protocol()
。
$dompdf->set_protocol(WWW_ROOT);
$dompdf->set_base_path('/');
WWW_ROOT
这里是一个指向我应用程序的webroot文件夹的CakePHP常数。注意,它有一个尾随斜杠。
最重要的是,这似乎是对set_protocol()
的不当使用。但是,只要它能使CSS工作,我就不会介意。
希望这能节省别人几个小时的时间。
发布于 2022-06-17 12:21:58
除了@Jurian Sluiman的答案之外,我还必须允许Dompdf访问基本路径,这样CSS样式和图像才能正常工作:
$dompdf = new Dompdf(['chroot' => __DIR__]);
$dompdf->setBasePath(__DIR__ . '/path/to/assets/'));
$dompdf->loadHtml($html);
$dompdf->render();
https://stackoverflow.com/questions/17185531
复制相似问题