CakePHP 和 FPDF:headers 用于在浏览器中查看

CakePHP and FPDF: headers for view in browser

我发现了很多关于 下载 pdf 文件要使用哪些 header 的问题。 相反,我想 在线查看 它们(即使用嵌入式 Chrome 插件)并可选择使用它下载它们。

这是我的 CakePHP 3.7.9 代码:

pdf.ctp

<?php
    header('Content-Type: application/pdf');
    require_once(ROOT . DS . 'vendor' . DS . 'fpdf182' . DS . 'fpdf.php');

    $pdf = new FPDF();
    $pdf->AddPage();
    $pdf->SetFont('Arial','B',16);
    $pdf->Cell(40,10,'Hello World!');
    $pdf->Output();

相关控制器的函数为空。我要把要打印的变量放在那里。 浏览到测试 pdf 页面我得到 un-decoded 数据:

%PDF-1.3 3 0 obj <> endobj 4 0 obj <> stream x�3R��2�35W(�r Q�w3T04�30PISp �Z*�[����(hx����+���(j*�d��7W endstream endobj 1 0 obj <> endobj 5 0 obj <> stream x�]R�n�0��>��L�%�DI�8���~�%Er�ﻻvҪHX�gvVk?/���Ῑ��`]�[�x5 �3\z��P�}����PO���j�Jݍ^���x6/f�����������|���4}�z�����}���@�,ۖ-��˺E�u�^�,���<� �Z_�K� IQ����Yd����C�K�_�%q�8>�!J"V!2&bGģ%r"H��D��}2EL1n��h�j���e��"aH����:��d��9c���[�X1~��"�3�g��Ñ�;O��> endobj 2 0 obj << /ProcSet [/PDF /Text /ImageB /ImageC /ImageI] /Font << /F1 6 0 R >> /XObject << >> >> endobj 7 0 obj << /Producer (FPDF 1.82) /CreationDate (D:20191229180430) >> endobj 8 0 obj << /Type /Catalog /Pages 1 0 R >> endobj xref 0 9 0000000000 65535 f 0000000228 00000 n 0000000867 00000 n 0000000009 00000 n 0000000087 00000 n 0000000315 00000 n 0000000749 00000 n 0000000971 00000 n 0000001047 00000 n trailer << /Size 9 /Root 8 0 R /Info 7 0 R >> startxref 1096 %%EOF

我很清楚浏览器是按字面意思读取内容,而不是将其解码为 pdf。 application/pdf header 还不够吗? 我还需要其他哪些 header?

如前所述,因为我不想默认下载文件,所以我没有设置文件名。

使用CakePHP时不要直接使用header(),也不要尝试手动向浏览器发送数据,那样只会出问题,总是使用CakePHP响应对象提供的抽象接口!

如果想在view层设置header,使用$this->response,渲染后返回给controller。然而,我有点倾向于争辩说视图 template 通常不应该真正做出这样的决定,视图本身,这更合理,而且大多数时候控制器层会是合适的地方。

无论如何,它在控制器、视图和视图模板级别上的工作方式相同,所以这里有一个示例:

$this->response = $this->response->withType('pdf');
$this->response = $this->response->withHeader(
    'Content-Disposition', 'inline; filename="some.pdf"'
);

请注意,您不能使用 withDownload(),因为它将使用 attachment 而不是 inline

此外,如果您使用视图模板,则应仅回显 PDF 内容,即相应地使用 FPDF::Output() 方法的 $dest 参数:

echo $pdf->Output('S'); // S = return String

另见