HTML2PDF - 下载并显示pdf文件到页面

时间:2016-05-10 18:16:38

标签: php laravel laravel-5.1 html2pdf

我在Laravel 5.1中使用HTML2PDF。我在页面上显示pdf文件并将其下载到服务器时遇到问题。

当我使用此代码时,它会显示pdf文件没有问题:

function is_multidimensional(array $array) {
    return count($array) !== count($array, COUNT_RECURSIVE);
}

但是,上面的代码不会将文件保存到服务器。所以我尝试了这个:

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

我在Chrome和Firefox中尝试过此功能,但它不显示文档,只是将文件下载到服务器。我做错了什么?

3 个答案:

答案 0 :(得分:1)

你可能真的想要这样做:

cmd = [command, path2Script] + args
x = subprocess.check_output(cmd,universal_newlines = True)

或者可能:

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

我无法从文档中看出来,但我不相信带有'F'选项的$filename = '\Report-' . $project->id . '.pdf'; $output_path = base_path() . '\public\reports' . $filename; $pdf = $html2pdf->Output($output_path, 'F'); return response($html2pdf->Output($output_path, 'S')) ->header('Content-Type', 'application/pdf') ->header('Content-Length', strlen($pdf)) ->header('Content-Disposition', 'inline; filename="'.$filename.'"'); 会返回'S'所在的文件内容。所以你只需要加载内容并返回它们。

答案 1 :(得分:1)

一点都不熟悉laravel,但考虑简单地将输出的pdf作为任何URL链接启动,因为现代浏览器将它们呈现为页面。下面假设pdf保存到服务器并作为响应对象:

$filename = '\Report-' . $project->id . '.pdf';
$output_path = base_path() . '\public\reports' . $filename;
$pdf = $html2pdf->Output($output_path, 'F'); 
return response($output_path)
    ->header("Location: $output_path ");

答案 2 :(得分:0)

我不知道这是否是最佳解决方案,但这有效:

$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.'"');

我注意到$pdf = $html2pdf->Output('', 'S');时,浏览器会显示该文件,但不会下载该文件。但是,如果$pdf = $html2pdf->Output($output_path, 'F');,浏览器不会显示该文件,但会下载它。所以我意识到,由于我正在response($pdf),我已将$html2pdf->Output('', 'S');分配给$pdf。由于我需要下载该文件,因此我只是$html2pdf->Output($output_path, 'F');,而没有将其分配给$pdf

希望我能正确解释这一点。我不知道这是否有一些漏洞或者这不是一个好的做法,但我会坚持一段时间,因为我还没有找到另一种工作方式。

感谢所有回答的人。