28

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?

Alfred Huang
  • 17,654
  • 32
  • 118
  • 189
saad
  • 581
  • 1
  • 6
  • 11
  • 3
    Have you tried `$stylesheet = '';`? I guess `pdf.css` contains only css so you have to _tell_ `html` that this is css. – Leri Mar 20 '13 at 09:13
  • it is working on local but not when i apply it at online server :( – saad Mar 20 '13 at 12:55
  • did you make it work in the online server? I'm facing a similar problem – Shankar Jul 25 '16 at 10:02
  • I find this library is easy to use as it supports HTML5 and css 3 because it is chrome based. https://github.com/spiritix/php-chrome-html2pdf – Krishnadas PC Feb 15 '21 at 10:06

1 Answers1

41
 <?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.

Haseeb
  • 2,214
  • 1
  • 22
  • 43
  • have one doubt. in my pdf 'padding' for 'li' tag is not working? Do we strictly need follow 'table' structure in pdf? – ARUN Feb 02 '15 at 08:58
  • 2
    how can I add multiple css file? – J.K.A. Oct 07 '15 at 06:38
  • 2
    @Mark you can add multiple css like this $stylesheet = file_get_contents('css/bootstrap.min.css'); $stylesheet .= file_get_contents('css/AdminLTE.min.css'); – Santosh Ram Kunjir Sep 08 '16 at 12:54
  • 1
    i am using using https://packagist.org/packages/niklasravnsborg/laravel-pdf and i am unable to use inline css. like float, display, etc. What should i do? – Anmol G Mar 20 '18 at 11:58
  • if the css file is large like bootstrap it produces thousands of empty pages... :/ – Sumit Wadhwa Jul 02 '21 at 11:39