我正在创建一个带有 TYPO3 扩展名“web2pdf”的 pdf 文件。我可以在桌面上下载该文件,但在移动设备上遇到两个不同的错误。
- IOS 只是显示与调试 $pdf 相同的代码(见下文)
- Android 取消下载并告诉我“服务器错误”
目前我只是想打印 PDF(触发器是前端按钮)
$pdf = $this->getResultPDF();
print($pdf)
$pdf 返回给我这个
string(160607) "%PDF-1.4 %���� 3 0 obj <> /Annots [ 17 0 R 18 0 R ] /Contents 4 0 R>> endobj 4 0 obj <> stream x��X�n�F�������H�����8n �Hb5]]��Ì(*!�����ʢw��y�deh����>�}Q~DjH��uk/&���$���V�yK�gWב\5���3y?�Y=��o9�s�w1�go" U4������=���+)����&��N2y��F$gs)�g9�D������5r�=�G��� �'vt}�x%��ǥ�J,�W�S19��\c��K�)�[��g��wt��ӥ��}E���\<�[�D:;P�1���գ�Ç+IJ�$!3�2���W鵙�a:�9�dj�$n����5X_��Z�_��Q�;/�X:NU��@+��l�k����RD�]�moi��\�Ͻӡ��Ň��18�"�8VqJv�k�ܘ`e��$���X��Ҽ�����NJ�a��X��O"5�,��z�b�"�d���S�}�......
正如我所说,这是我在桌面上工作的。 HTTP header 设置为默认(内容类型:Text/html)
一旦我将内容标题更改为“application/pdf”,下载就可以在所有设备上正常工作。但 PDF 文件现在似乎已损坏。我无法在任何程序中打开该文件。
我也尝试解码 $pdf 输出并将其放入文件中(说实话,我什至不知道这可能会有帮助):
pdf = $this->getResultPDF();
$binary = base64_decode($pdf);
file_put_contents('filename.pdf', $binary);
header('Content-disposition: attachment;filename="filename.pdf"');
header('Content-Type: application/pdf');
header('Content-Description: File Transfer');
header('Pragma: public');
print($binary);
我是否使用了错误的 php 函数来下载 pdf?在移动设备上下载 PDF 是否需要任何特定的标题?
最佳答案
应该足够了:
// force download in the browser
header('Content-Disposition: attachment; filename="filename.pdf"');
// tell the browser it's a pdf document
header('Content-Type: application/pdf');
// don't allow to cache
header('Cache-Control: private');
// if you have pdf contents in a variable report its size
// otherwise the browser won't show download progress
// you should skip this line for large files
header('Content-Length: ' . strlen($pdf));
// flush the output directly
// don't do this for large files
readfile($pathToThePdf);
// OR
// output in chunks for large files
$handle = fopen($pathToThePdf);
while (!feof($handle)) {
$buffer = fread($handle, 8192);
if (false !== $buffer) {
echo $buffer;
}
}
fclose($handle);
如果您遇到任何 500 错误,那么您应该检查错误日志中是否有错误,为什么会发生这种情况。
关于php - pdf 下载的正确 HTTP header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61730067/