我使用的是带有Laravel 5.1的HTML2PDF。我在页面上显示pdf文件并将其下载到服务器时遇到问题。
当我使用这个代码时,它显示的pdf文件没有问题:
$pdf = $html2pdf->Output('', 'S');
return response($pdf)
->header('Content-Type', 'application/pdf')
->header('Content-Length', strlen($pdf))
->header('Content-Disposition', 'inline; filename="sample.pdf"');
但是,上面的代码并没有将文件保存到服务器。所以我尝试了这个:
$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.'"');
我在Chrome和Firefox中尝试过,但它不显示文档,只是将文件下载到服务器。我做错了什么?
你可能真的想这么做:
$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.'"');
或者可能:
$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.'"');
我无法从文档中判断,但我不相信带有"F"选项的Output
会返回"S"所返回的文件内容。因此,您只需要加载内容并返回这些内容。
对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 ");
我不知道这是否是最好的解决方案,但这很有效:
$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
。
希望我能解释清楚。我不知道这是否有漏洞,或者这不是一个好的做法,但我会坚持一段时间,因为我还没有找到另一种方法。
感谢所有回答的人。