nishimura.clubnishimura.club

laravel-dompdf × Vue.js で PDF出力

作成日
2021-09-07
更新日
2021-09-07

ドキュメント

Laravel実装

インストール

# インストール composer require barryvdh/laravel-dompdf # 設定 php artisan vendor:publish --provider="Barryvdh\DomPDF\ServiceProvider"

実装

PdfController.php
public function htmlToPdf() { $pdf = App::make('dompdf.wrapper'); $pdf->loadHTML('<h1>Test PDF</h1>'); return $pdf->stream(); }
api.php
Route::get('pdf/html-to-pdf', 'Api\PdfController@htmlToPdf');

JavaScript実装(Vue.js)

Vue.jsはあまり関係ないですが、APIサーバとしてLaravelを採用している場合の、JS側での$pdf->stream();の受け取り処理です。

vue.js - Download PDF with laravel-dompdf with vuejs front-end - Stack Overflow を参考に

実装

// axios で API Call const response = await this.axios.get('/pdf/html-to-pdf', { responseType: 'blob' }) // Response 確認 console.log('response: ', response) // blobURL作成 const url = window.URL.createObjectURL(new Blob([response.data])) // ダウンロード const link = document.createElement('a') link.href = url link.setAttribute('download', 'markdown.pdf') document.body.appendChild(link) link.click()

POSTの例

BODYhtmlStringが入ってくる。

PdfController.php
public function htmlToPdf(Request $request) { $htmlString = $request->input('htmlString'); $html = <<< DOC_END <!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <style type="text/css"></style> </head> <body> $htmlString </body> </html> DOC_END; $pdf = App::make('dompdf.wrapper'); $pdf->loadHTML($html); return $pdf->stream(); }

日本語化について

Mac Laravelのライブラリ「laravel-dompdf」を日本語表示に対応させる - Qiita を参考に

メモ

php load_font.php ipag fonts/ipag.ttf cp -r vendor/dompdf/dompdf/lib/fonts storage/ # 必要ないかも chmod 777 storage/fonts/* php artisan optimize:clear

Related