打开 pdf laravel 时出错(无法在浏览器中正确显示)

Error opening pdf laravel (not display correctly in browser)

我在从 laravel 中的目录打开现有 pdf 时遇到问题。该代码与纯 PHP 完美配合,但将其带到 laravel 却无法正常工作,因为它无法在浏览器中正确显示,它看起来像这样:

%PDF-1.5 3 0 obj <> /Contents 4 0 R>> endobj 4 0 obj <> stream x�}��NAE����1��E=��bq~��I�� � �= .....

代码如下:

//eval_pdf.blade.php

File::requireOnce('fpdf.php');
File::requireOnce('fpdi.php');
$pdf = new FPDI('P','mm','Letter');
$pdf->AddPage();
$pdf->SetAutoPageBreak(true,10);  
$sourceFileName = app_path().'/include/formato.pdf';
$pdf->setSourceFile($sourceFileName);
$tplIdx = $pdf->importPage(1);
$pdf->useTemplate($tplIdx);
$pdf->SetFont('helvetica','B',8);
 .
 .
 .
$pdf->SetXY(86, 21);
$pdf->Write(0, utf8_decode($comp));
.
.
.
$pdf->Output();

可能是什么问题以及如何解决?

你应该使用这样的东西:

而不是$pdf->Output();

使用:

$pdfContent = $pdf->Output('', "S");

将内容保存到字符串中

然后 return 响应 例如:

    return response($pdfContent, 200,
        [
            'Content-Type'        => 'application/pdf',
            'Content-Length'      =>  strlen($pdfContent),
            'Content-Disposition' => 'attachment; filename="mypdf.pdf"',
            'Cache-Control'       => 'private, max-age=0, must-revalidate',
            'Pragma'              => 'public'
        ]
    );