php - 将 CSS 文件包含到 mpdf
问题描述
我正在尝试为我的 mPDF 文件实现一个 CSS 文件。这是我的 mPDF 文件:
$pdf_output = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>' . get_bloginfo() . '</title>';
$cssFile = __DIR__.DIRECTORY_SEPARATOR.'styles.css';
// echo $cssFile;
if (file_exists($cssFile)) {
$pdf_output .= '<style type="text/css">'.file_get_contents($cssFile).'</style>';
}
$pdf_output .= '</head>
<body xml:lang="en">
<pagebreak>
<div id="header"><div id="headerimg">
<h1><a href="' . get_option('home') . '/">' . get_bloginfo('name') . '</a></h1>
<div class="description">' . get_bloginfo('description') . '</div>
</div>
</div>
<div id="content" class="widecolumn"><div id="test">Lorem ipsum dolorem sit amet</div>';
if(have_posts()) :
while (have_posts()) : the_post();
$pdf_output .= '<div class="post">
<h2>' . $pageTitle . '</h2>';
$pdf_output .= '<div class="entry">POST: ' . wpautop($post->post_content, true) . '</div>';
$pdf_output .= '</div> <!-- post -->';
endwhile;
else :
$pdf_output .= '<h2 class="center">Not Found</h2>
<p class="center">Sorry, but you are looking for something that isn\'t here.</p>';
endif;
$pdf_output .= '</div> <!--content-->';
$pdf_output .= '
</body>
</html>';
styles.css 所说的所有内容都被完全忽略,就好像文件甚至没有加载一样。有趣的是,如果我附加
echo '<pre><div id="output">'.$pdf_output.'</div></pre>';
exit;
最后,我得到了一个 HTML 页面,一切正常。我的错误到底在哪里?我想这是 mPDF 设置中的某种选项。
解决方案
OP从评论中找到了解决方案,所以我将在此处添加它只是为了结束:
似乎 mPDF 不支持样式标签中的 CSS(请参见此处:https ://mpdf.github.io/css-stylesheets/introduction.html )。在这种情况下,您可以替换它:
$cssFile = __DIR__.DIRECTORY_SEPARATOR.'styles.css';
if (file_exists($cssFile)) {
$pdf_output .= '<style type="text/css">'.file_get_contents($cssFile).'</style>';
}
这样:
$cssFile = __DIR__.DIRECTORY_SEPARATOR.'styles.css';
if (file_exists($cssFile)) {
$pdf_output .= '<link rel="stylesheet" href='.$cssFile.'></link>';
}
或者使用调用 mPDF 的 WriteHTML() 两次的替代方法,一次用于样式表,另一次用于正文,如上面文档中的示例。
推荐阅读
- python - python正则表达式从字符串(文本)列表中获取日期和价格
- flutter - pubspec.lock 的第 3 行第 1 列出错:只需要一个文档
- python - 拓扑排序给出不正确的结果
- c# - 带有 Swashbuckle 的 ASP.NET Core 使用继承和集合
- python - 使用 Cloud Function 和 Python 创建警报策略 - 位置参数错误
- linux - 在构建之前创建 dotenv 文件并使用 GitHub Actions 部署到 dockerhub
- r - 如何更改R中变量的类型?
- javascript - 反应由多个组件处理的拖放
- gnu-make - gnumake:执行配方中的每个空格分隔的单词
- spring-boot - 如何使用 Uniswap v3 GraphQL API 获取代币价格