【问题标题】:Including CSS file to mpdf将 CSS 文件包含到 mpdf
【发布时间】:2020-11-05 23:24:29
【问题描述】:

我正在尝试为我的 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 设置中的某种选项。

【问题讨论】:

  • 能否请您发布使用此 HTML 代码生成 PDF 文件的代码?
  • 我正在使用 mPDF Wordpress 插件
  • 看来 mPDF 不支持样式标签上的样式,请在此处检查:mpdf.github.io/css-stylesheets/introduction.html — 如果您使用链接标签或使用设置两个不同调用的示例,它可能会正常工作WriteHTML 方法,其中一个使用 CSS,另一个设置 HTML 正文
  • @Melanef 链接标签对我有用。谢谢!

标签: php html css pdf mpdf


【解决方案1】:

OP从cmets中找到了解决方案,所以我在这里添加它只是为了关闭:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-11
    • 1970-01-01
    • 2016-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-02
    • 2015-12-05
    相关资源
    最近更新 更多