Search code examples
phplaravellaravel-5.1html2pdf

HTML2PDF - Download and display pdf file to page


I am using HTML2PDF with Laravel 5.1. I have a problem with showing the pdf file on the page and downloading it to the server.

When I use this code, it shows the pdf file without problems:

$pdf = $html2pdf->Output('', 'S'); 
return response($pdf)
    ->header('Content-Type', 'application/pdf')
    ->header('Content-Length', strlen($pdf))
    ->header('Content-Disposition', 'inline; filename="sample.pdf"');

However, the above code does not save the file to the server. So I tried this:

$filename = '\Report-' . $project->id . '.pdf';
$output_path = base_path() . '\public\reports' . $filename;
$pdf = $html2pdf->Output($output_path, 'F'); 
return response($pdf)
    ->header('Content-Type', 'application/pdf')
    ->header('Content-Length', strlen($pdf))
    ->header('Content-Disposition', 'inline; filename="'.$output_path.'"');

I've tried this in Chrome and in Firefox but it does not display the document, it just downloads the file to the server. What am I doing wrong?


Solution

  • I don't know if this is the best solution, but this works:

    $filename = 'Report-' . $project->id . '.pdf';
    $output_path = base_path() . '\public\reports\\' . $filename;
    $pdf = $html2pdf->Output('', 'S');
    $html2pdf->Output($output_path, 'F');
    return response($pdf)
       ->header('Content-Type', 'application/pdf')
       ->header('Content-Length', strlen($pdf))
       ->header('Content-Disposition', 'inline; filename="'.$filename.'"');
    

    I noticed that when $pdf = $html2pdf->Output('', 'S');, the browser displays the file but does not download the file. However, if $pdf = $html2pdf->Output($output_path, 'F');, the browser does not display the file, but downloads it nevertheless. So I realized that since I'm doing response($pdf), I assigned $html2pdf->Output('', 'S'); to $pdf. And since I need to download the file, I just did $html2pdf->Output($output_path, 'F');, without assigning this to $pdf.

    Hope I explained this properly. I don't know if this has some loopholes or this is not good practice, but I'm going to stick to this for a while since I have not yet found another way for this to work.

    Thank you for all those who answered.