首页 > 解决方案 > 将 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 设置中的某种选项。

标签: phphtmlcsspdfmpdf

解决方案


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() 两次的替代方法,一次用于样式表,另一次用于正文,如上面文档中的示例。


推荐阅读