Html to pdf

Submitted by meertensm - 1 year ago

A function to convert a html string to a pdf string using wkhtmltopdf. This function doesn't use any temporary files and is plugin independent. Update: I've created a composer package from this function. See: https://github.com/meertensm/HtmlToPdf

function toPdf($html, $landscape = false)
{
    
    $wkhtmltopdf = '/usr/local/bin/wkhtmltopdf';

    // Take advantage from laravel's environment variables
    // $wkhtmltopdf = env('WKHTMLTOPDF');

    $descriptorspec = [
        0 => ['pipe', 'r'], // stdin
        1 => ['pipe', 'w'], // stdout
        2 => ['pipe', 'w']  // stderr
    ];

    // unset DYLD_LIBRARY_PATH as a workaround for common errors when working on a mac with a MAMP stack
    $process = proc_open('unset DYLD_LIBRARY_PATH ;' . $wkhtmltopdf . ' ' . ( $landscape ? '-O landscape' : '' ) . ' -q - -', $descriptorspec, $pipes);

    // Send the HTML on stdin
    fwrite($pipes[0], $html);
    fclose($pipes[0]);

    // Read the outputs
    $pdf = stream_get_contents($pipes[1]);
    $errors = stream_get_contents($pipes[2]);

    // Close the process
    fclose($pipes[1]);
    $return_value = proc_close($process);

    if ($errors){
        dd($errors);
    }else{
        header('Content-Type: application/pdf'); 
        echo $pdf;
    }
}
comments powered by Disqus

Ads cover the costs of maintaining Laravel-tricks