php下載PDF文件

前言

項目近期有個業務需求:下載PDF版發票。和公司前輩溝通,有兩種方案php

  • 先作成圖片,把動態數據用畫布座標的形式填充進去,把圖片放進PDF文件中,再下載(比較繁瑣)
  • 先用html畫頁面,再轉成PDF文件,再下載(決定用這種方式)

1、安裝依賴

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

2、代碼演示

$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);

3、可能遇到的問題

  1. 若是出現PDF文件下載下來,中文亂碼的狀況,那是由於缺乏一個字體文件,下載這個字體simsun.ttc,把它添加到/usr/share/fonts目錄。
相關文章
相關標籤/搜索