#StackBounty: #php #html #css #pdf #dompdf Convert html with styling (css) to pdf using dompdf and PHP

Bounty: 100

I’m having some problems with my code! I am trying to convert my html invoice to a pdf invoice. This is the invoice I’m using: invoice. But when I convert the html to pdf the styles are not applied and the images don’t show.

This is my PHP code to convert the html to a pdf using DomPDF:

require 'vendor/autoload.php';
// reference the Dompdf namespace

$files = glob("/invoices/*.pdf");

foreach ($files as $file) include_once($file);

// instantiate and use the dompdf class
$dompdf = new Dompdf();
$dompdf->setPaper('A4', 'portrait'); //landscape / portrait

$options = new Options();
$options->set('isRemoteEnabled', true);
$options->set('defaultFont', 'OpenSans');

// Render the HTML as PDF

$output = $dompdf->output();
file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/invoices/" . $order_id . ".pdf", $output);

I think my problem lies with the HTML code.

The problem with the css

I’ve tried a couple of things but none of these worked for me! Here’s what I tried:

Try 1

I’ve tried adding the css with a link tag like this:

$html .= '<link type="text/css" href="/absolute/path/to/pdf.css" rel="stylesheet" />';
I’ve also tried adding the link like a normal (in the head of the file), but both these times I didn’t got it working.

Try 2

I’ve also tried putting the css in a style tag in the head like this:

    /* my css here */

This didn’t work eighter. I’m running out of ideas for the css.

The problem with the images

When the html code contains a img like this:

<img src="/path/to/file" alt="" />

The image doesn’t show up. Not even when I change the src to https://pathtoimg.com/path/to/file/img.png

Hopefully, you know the solution to the image and the css problems I’m struggling with! Thanks already for your effort!

Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.