php PDFファイルのダウンロード

2466 ワード

前言
プロジェクトの最近のビジネスニーズ:PDF版請求書をダウンロードします.会社の先輩とコミュニケーションするには、二つの案があります.
  • まず画像を作成し、ダイナミックデータをキャンバス座標の形で埋め込み、画像をPDFファイルに入れてからダウンロード(煩雑)
  • htmlでページを描き、PDFファイルに変換してからダウンロード(この方式で決定)
  • 一、インストール依存
    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

    次のエラーが発生した場合は、上の2行目のコマンドと3行目のコマンドを繰り返します.
    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);

    三、直面する可能性のある問題
  • PDFファイルがダウンロードされ、中国語が文字化けしている場合は、フォントファイルが1つ足りないため、このフォントsimsunをダウンロードします.ttcは、/usr/share/fontsディレクトリに追加します.