32

I am trying to convert html into pdf using mpdf. Problem is that i am unable to apply css to pdf file..

Here is my code of php:

<?php

    $html = $divPrint;
    $mpdf=new mPDF();
    $stylesheet = file_get_contents('pdf.css');
    $mpdf->WriteHTML($stylesheet,1);
    $mpdf->WriteHTML($html,2);
    $mpdf->Output();
    exit;

?>

What it is doing is taking html through ajax on my this php page. But the output it gives doesn't come with css which i've written for it..

Please tell me that to do now?

4
  • 3
    Have you tried $stylesheet = '<style>'.file_get_contents('pdf.css').'</style>';? I guess pdf.css contains only css so you have to tell html that this is css. Commented Mar 20, 2013 at 9:13
  • it is working on local but not when i apply it at online server :( Commented Mar 20, 2013 at 12:55
  • did you make it work in the online server? I'm facing a similar problem Commented Jul 25, 2016 at 10:02
  • I find this library is easy to use as it supports HTML5 and css 3 because it is chrome based. github.com/spiritix/php-chrome-html2pdf Commented Feb 15, 2021 at 10:06

1 Answer 1

43
 <?php

$html = $divPrint;

include('mpdf.php'); // including mpdf.php
$mpdf=new mPDF();
$stylesheet = file_get_contents('pdf.css'); // external css
$mpdf->WriteHTML($stylesheet,1);
$mpdf->WriteHTML($html,2);
$mpdf->Output();
exit;

?>

1st assign your html in $html then include mpdf.php file.

Sign up to request clarification or add additional context in comments.

5 Comments

have one doubt. in my pdf 'padding' for 'li' tag is not working? Do we strictly need follow 'table' structure in pdf?
how can I add multiple css file?
@Mark you can add multiple css like this $stylesheet = file_get_contents('css/bootstrap.min.css'); $stylesheet .= file_get_contents('css/AdminLTE.min.css');
i am using using packagist.org/packages/niklasravnsborg/laravel-pdf and i am unable to use inline css. like float, display, etc. What should i do?
if the css file is large like bootstrap it produces thousands of empty pages... :/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.