2016-12-02 121 views
0

我要預覽並使用此代碼下載訂單發票PDF:PDF數據顯示,但文件沒有下載

public function generatePDFByIdOrder() 
    { 
     $order = new Order(1); //I want to download the invoice PDF of $order_id '1' 
     if (!Validate::isLoadedObject($order)) { 
      throw new PrestaShopException('Can\'t load Order object'); 
     } 

     $order_invoice_collection = $order->getInvoicesCollection(); 
     $this->generatePDF($order_invoice_collection, PDF::TEMPLATE_DELIVERY_SLIP); 
    } 

    public function generatePDF($object, $template) 
    { 
     $pdf = new PDF($object, $template, Context::getContext()->smarty); 
     $pdf->render(); 
    } 

並用下面的代碼調用它: $order = new order(); echo $order->generatePDFByIdOrder();

我有PDF格式的數據打印在瀏覽器控制檯上但未下載。 enter image description here

如何操作該數據以下載pdf文件?

+1

你可能需要添加一個合適的'頭()' – Jakuje

回答

1

PrestaShop使用TCPDF。

編輯generatePDF這樣:

public function generatePDF($object, $template) 
{ 
    $pdf = new PDF($object, $template, Context::getContext()->smarty); 
    $pdf->Output('name.pdf', 'I'); 
} 
+0

奇怪,我有'未捕獲的錯誤:調用未定義的方法PDF ::輸出() '。 – androniennn

+0

PrestaShop版本? –

+0

1.6.1.9版本。 – androniennn

0

我猜你僅僅使用TCPDF渲染PDF像這樣之前設置適當的標題:

header("Content-type:application/pdf"); 

但是,「下載」一個PDF會取決於用戶的瀏覽器設置。它可能會下載它們(在這種情況下,您必須設置另一個名爲Content-Disposition:attachment的標頭)或將其顯示在瀏覽器中。

+0

,我不應該改變'$ pdf-> render();'輸出'? – androniennn

0

我們建議您創建一個單獨的控制器來渲染PDF文件並始終在新選項卡中打開該控制器。它將幫助您使用DOMPDF庫具有單獨的邏輯。

發票控制器將如下(invoice.php)

include_once(_PS_MODULE_DIR_.'supercehckout/libraries/dompdf/dompdf_config.inc.php'); 

class SuperCheckoutInvoiceModuleFrontController extends ModuleFrontController 
{ 
    public function initContent() 
    { 
       parent::initContent(); 
       $this->generateInvoice(ORDER_ID); 
    } 
} 

注:SuperCheckout是該例子的模塊名稱。

generateInvoice()函數如下:

function generateInvoice($order_id) 
{ 
     $dompdf = new DOMPDF(); 
     $html = utf8_decode(INVOICE_HTML); 
     $dompdf->load_html(INVOICE_HTML); 
     $dompdf->render(); 
}