doutan2456
2015-07-07 01:00
浏览 126

通过PHP下载PDF不会在手机上打开

Generating a PDF from wkhtmltopdf working great on desktop. I have a two-step process to generate the file and then download the file. The file generated opens just fine on my mobile device (when I e-mail it) but using a PHP script, I am unable to open after download.

In other words, it's not the PDF, it's the PHP download that's causing problems. The file downloads with the appropriate name, but won't open in mobile.

Galaxy S5 w/ Chrome (up-to-date).

The download is started with javascript:

window.location = 'savePDF.php?file=' + filename + '&fileName=' + nameString;

And here's the PHP script:

<?php
$file = $_GET['file'];

header('Pragma: public',true);
header('Expires: 0');
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/octet-stream");
header('Content-Disposition: attachment; filename="'.$_GET['fileName'].'.pdf"');
header("Content-Transfer-Encoding: binary");
header('Content-Length: ' . filesize($file));
readfile($file);
unlink($file);
?>

EDIT: unlink($file) added to code to show that aspect.

图片转代码服务由CSDN问答提供 功能建议

从wkhtmltopdf生成一个在桌面上运行良好的PDF。 我有两个步骤来生成文件,然后下载文件。 生成的文件在我的移动设备上打开就好了(当我通过电子邮件发送时)但是使用PHP脚本,我无法在下载后打开 。

换句话说,它不是PDF,而是导致问题的PHP下载。 该文件以适当的名称下载,但不会在移动设备中打开。

Galaxy S5 w / Chrome(最新版)。

下载以javascript开始:

  window.location ='savePDF.php?file ='+ filename +'&amp;  fileName ='+ nameString; 
   
 
 

这里是PHP脚本:

  &lt;?php 
 $ file = $ _GET ['file']; 
 
header('Pragma:public',true); 
header('Expires:0'); 
header(“Cache-  Control:must-revalidate,post-check = 0,pre-check = 0“); 
header(”Content-Type:application / octet-stream“); 
header('Content-Disposition:attachment; filename =”'  。$ _ GET ['fileName']。'。pdf“'); 
header(”Content-Transfer-Encoding:binary“); 
header('Content-Length:'。filesize($ file)); 
readfile(  $ file); 
unlink($ file); 
?&gt; 
   
 
 

编辑: unlink($ file)添加到代码 显示这个方面。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanhuangyun3887 2015-07-07 20:34
    已采纳

    Figured it out. Thanks to everyone for helping me debug (on mobile without dev tools it is a pain).

    I was unlink($file); right after readfile($file) and for some reason on mobile (when it was asking what I wanted to do with the file before downloading) it was deleting the temporary file before reading the entire contents. Instead, I added:

    exec("php cleantmp.php $tmpfile > NUL &");
    

    and created cleantmp.php:

    <?php
    if (php_sapi_name() == 'cli') {
        sleep(10);
    
        unlink($argv[1]);
    }
    ?>
    

    Which now runs in the background and deletes the temp files after 10 seconds.

    Thanks again for your help CBroe

    点赞 打赏 评论

相关推荐 更多相似问题