Search code examples
laraveltcpdfdompdftailwind-cssmpdf

Laravel - Outputting a view styled with TailwindCSS as PDF


I'm trying to make generate a pdf from a view but the styles just won't come out. I've tried using 3 different libraries but the results aren't much different. Am I missing something?

view

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Test View</title>
  <link rel="stylesheet" type="text/css" media="screen" href="{{ asset('css/app.css') }}">
  <script src="{{ asset('js/app.js') }}" defer></script>
</head>
<body class="font-sans antialiased">

<div class="grid grid-cols-3">
  <div class="bg-red-200 col-span-2 h-screen"></div>
  <div class="bg-blue-200 h-screen">
    <div class="grid grid-cols-8">
      <div class="col-span-7">
        <div class="rounded-t-full w-full h-screen flex items-center justify-center bg-green-600">
          <div class="h-60 w-60 rounded-full bg-blue-500">TEST</div>
        </div>
      </div>
    </div>
  </div>
</div>

</body>
</html>

appearance

enter image description here


dompdf export method

protected function dompdfImplementation()
{
    $dompdf = new Dompdf;
    $dompdf->getOptions()->setChroot(public_path());
    $dompdf->loadHtml(view('view')->render());

    $dompdf->stream('view.pdf', ['Attachment' => false]);
}

dompdf export result

enter image description here


mpdf export method

protected function mpdfImplementation()
{
    $mpdf = new Mpdf;
    $mpdf->WriteHTML(view('view')->render());

    $mpdf->output();
}

mpdf export result

enter image description here


tcpdf export method

protected function tcpdfImplementation()
{
    $tcpdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
    $tcpdf->AddPage();
    $tcpdf->writeHTML(view('view')->render());

    $tcpdf->Output('view.pdf', 'I');
}

tcpdf export result

enter image description here


Is it not possible to export views to pdf without a css inliner?

Am I better off just manually taking a full page screenshot, pasting it into a text document and saving it as a pdf file?


Solution

  • After

    • trying barryvdh/laravel-dompdf instead of dompdf/dompdf
    • using media="print" on my stylesheet
    • using TailwindCSS's print:* classes
    • trying to get chrome-php to work to no avail
    • trying barryvdh/excel's pdf exports.

    Nothing worked so the solution I have reached is a bad one.

    1. Open view in firefox.
    2. Screenshot whole page (not just visible content).
    3. Use the first online PNG to PDF converter I find.

    I wish there'd be a less painful way to do this but it doesn't look like it. This bad solution actually works.