2013-03-22 99 views
-1

我想在用戶成功提交表單後下載PDF文件。PHP:試圖使pdf文件可下載

我已經使用了this question的代碼,但是pdf文件的內容被輸出爲gebrish字符而不是彈出的下載對話框。

下載代碼從功能

function phpfmg_thankyou(){ 
    phpfmg_redirect_js(); 

    //include('get_file.php'); 
    $pdf_file = "{$_SERVER['DOCUMENT_ROOT']}/secured_assets/CRE_White_Paper_Release_01-15-2013.pdf"; 
    if(file_exists($pdf_file)){ 
     header("Content-Type: application/octet-stream"); 
     header("Content-Disposition: attachment; filename=" . Urlencode('CRE_White_Paper_Release_01-15-2013.pdf')); 
     header("Content-Type: application/force-download"); 
     header("Content-Type: application/download"); 
     header("Content-Description: File Transfer");    
     header("Content-Length: " . Filesize($pdf_file)); 
     flush(); // this doesn't really matter. 
     $fp = fopen($pdf_file, "r"); 
     while (!feof($fp)){ 
      echo fread($fp, 65536); 
      flush(); // this is essential for large downloads 
     } 
     fclose($fp); 

    } 

?> 

<!-- [Your confirmation message goes here] --> 
    <br> 

    <div style="padding: 1em; background: #CDD7B6;">  
     <b>Your inquiry has been received. Thank you!</b> 
     <p><a title="FREE White Paper Commercial Real Estate Expectations" href="secured_assets/CRE_White_Paper_Release_01-15-2013.pdf">Click Here</a> to get your FREE copy of White Paper Commercial Real Estate Expectations</p> 
    </div> 

<?php 



} // end of function phpfmg_thankyou() 

enter image description here

+0

顯示您在此處使用的代碼。 – Cfreak 2013-03-22 19:12:25

+0

看起來像忘記發送/不正確地發送內容類型標題。例如,'header(「Content-Type:application/octet-stream」);'你能向我們展示你的代碼嗎?特別重要的是,你要向我們展示文件頂部和「header(...)」調用之間的每一行(甚至是空白)。 – jedwards 2013-03-22 19:13:56

+0

我認爲你的頭文件不能被髮送,因爲已經輸出了...我也看到PDF後的HTML嗎? – Wrikken 2013-03-22 19:27:01

回答

0

這中調用僅僅是一種預感,但嘗試在你的PHP移除所有的HTML代碼:

<!-- [Your confirmation message goes here] --> 
    <br> 

    <div style="padding: 1em; background: #CDD7B6;">  
     <b>Your inquiry has been received. Thank you!</b> 
     <p><a title="FREE White Paper Commercial Real Estate Expectations" href="secured_assets/CRE_White_Paper_Release_01-15-2013.pdf">Click Here</a> to get your FREE copy of White Paper Commercial Real Estate Expectations</p> 
    </div> 

像這樣添加內容(我認爲)會讓你的客戶認爲HTML是PDF文件的一部分。 PDF文件被壓縮,任何非標準數據將最終導致整個事情變得亂七八糟,就像你描述的那樣。

瀏覽器會自動帶你回到你的下載文件(如果該文件設置爲自動下載)

因此,如果你想有一個三江源,你可以建立一個PHP頁面之前的原始頁面其中說「Thankyou」,然後將瀏覽器重定向到實際的下載PHP頁面。當下載發生時,您的Thankyou將仍然顯示。

我絕對不是PHP專業人士,所以如果我錯了,告訴我,我會刪除答案。

在試圖獲取文件下載之前,我會建議只是試圖讓PHP文件假裝它是一個PDF文件。這樣就會有更少的事情可能出錯。一旦你的PHP輸出一個PDF文件,你只需要添加適當的頭到你現有的代碼,使其自動下載。

0

謝謝大家的投入。我可以通過在提交後重定向到另一個頁面來解決此問題,並在該重定向頁面中包含下載代碼。