項目近期有個業務需求:下載PDF版發票。和公司前輩溝通,有兩種方案php
wkhtmltopdf依賴安裝(https://wkhtmltopdf.org/downloads.html) 能夠直接在官網下載安裝包,像服務器經過經過如下方式(找好對應的版本下載呦,我用的是ubantu 16)
wget https://downloads.wkhtmltopdf.org/0.12/0.12.5/wkhtmltox_0.12.5-1.xenial_amd64.deb apt-get install -f dpkg -i wkhtmltox_0.12.5-1.xenial_amd64.deb
若是出現如下錯誤,就重複下上面第二行命令和第三行命令html
dpkg: error processing package wkhtmltox (--install): dependency problems - leaving unconfigured Errors were encountered while processing: wkhtmltox
$outPut = view('invoice', [ 'orderData' => $orderData ])->render(); //invoice.blade.php是html模板,往裏填充動態數據 //將填充完整的html文件存儲起來,稍後用來轉PDF $htmlName = $this->getHtmlName();//獲取html文件名 $htmlDir = $this->getHtmlDir();//獲取 html 工做目錄 $htmlFullPath = storage_path($htmlDir . $htmlName); file_put_contents($htmlFullPath, $outPut); //設置pdf文件路徑 $pdfName = $this->getPdfName($orderData['order_no']);//獲取pdf文件名 $pdfDir = $this->getPDFDir();//獲取 pdf 工做目錄 $pdfFullPath = storage_path($pdfDir . $pdfName); //設置PDF文件的屬性 $pdf = new Pdf($htmlFullPath); $pdf->setOptions([ 'no-outline', //'zoom' => 3, 'margin-top' => 0, 'margin-right' => 0, 'margin-bottom' => 0, 'margin-left' => 0, //'disable-smart-shrinking', ]); //保存PDF if (!$pdf->saveAs($pdfFullPath)) { \Log::error('Could not create PDF:', [$pdf->getError()]); return false; }
由於咱們項目使用了多臺服務器,因此咱們就把PDF文件先上傳到oss再進行下載的,若是不須要能夠直接用Header方式下載服務器
header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=' . $pdfName); readfile($pdfFullPath);
/usr/share/fonts
目錄。