2017-11-18 254 views
2

我想在Laravel 5.5中使用tFPDF。我添加了作曲家包,然後我試圖輸出它根據docs,但沒有任何工作。Laravel 5:輸出tFPDF

我試圖輸出直接到瀏覽器:

Route::get('/test',function(){ 
     $pdfLibrary = new tFPDF\PDF(); 
     $pdfLibrary->AddPage(); 

     $pdfLibrary->AddFont('DejaVuSansCondensed', '', 'DejaVuSansCondensed.ttf', true); 
     $pdfLibrary->SetFont('DejaVuSansCondensed', '', 14); 

     $pdfLibrary->Write(8, 'Hallo!'); 
     $pdfLibrary->output();   
}); 

但sceen只是一片空白。當我試圖return $pdfLibrary->output(); 那麼它只是返回

%PDF-1.3 3 0 OBJ <> endobj 4 0 OBJ <>流許@S)> + P .... ...

我也試圖簡單的PDF格式保存到一個文件,但即使

沒有工作。如何保存&輸出由tFPDF創建的pdf?

回答

1

我終於意識到tFPDF的非官方作曲家版本稍微改變了output函數的行爲。輸出函數只返回pdf內容,但不能將其保存到文件中,也不能直接在瀏覽器中顯示。

所以不是

$pdfLibrary->output('file.pdf'); 

一個人如果沒有使用Laravel使用

Storage::put('file.pdf', $pdfLibrary->output()); 

file_put_contents

如果想使其直接在瀏覽器一個可以使用

return response()->file($pathToFile); 

最後一個音符:永遠不變的字體名稱。這會在DocnetUK/tfpdf版本中引發錯誤,但它當然在tfpdf的官方版本中起作用。

更新

另一件事,一個應該注意的是,非官方版本作曲家改變了方法tFPDF__construct,因爲命名空間的這是必要的(見What's difference between __construct and function with same name as class has?)。

然而,這意味着延長tfpdf類和在他們構造的所有類,需要調用這樣的父類的構造:

class Document extends \tFPDF\PDF 
{ 
    public function __construct(){ 
      parent::__construct(); 
      // ... your code for constructor. 
    } 

    //.... 

} 

而且變量名稱已更改:

  • $this->w =>$this->flt_current_width
  • $this->h =>$this->flt_current_height