# インストール composer require barryvdh/laravel-dompdf # 設定 php artisan vendor:publish --provider="Barryvdh\DomPDF\ServiceProvider"
PdfController.phppublic function htmlToPdf() { $pdf = App::make('dompdf.wrapper'); $pdf->loadHTML('<h1>Test PDF</h1>'); return $pdf->stream(); }
api.phpRoute::get('pdf/html-to-pdf', 'Api\PdfController@htmlToPdf');
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()
BODY
に htmlString
が入ってくる。
PdfController.phppublic 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