77 lines
2.7 KiB
PHP
77 lines
2.7 KiB
PHP
<?php
|
||
// app/controller/PdfController.php
|
||
namespace app\controller;
|
||
|
||
use support\Request;
|
||
use support\Response;
|
||
use support\View;
|
||
use app\common\utils\pdf\service\MpdfDriver;
|
||
use app\common\utils\pdf\service\PdfHelper;
|
||
|
||
class PdfController
|
||
{
|
||
// ① 从“现有 HTML 文件 + 外链CSS”生成并在线预览
|
||
public function previewFromFile(Request $request): Response
|
||
{
|
||
// 你的模板路径(示例)
|
||
$tpl = base_path('resource/templates/usedCar.html');
|
||
// 可选:把 {{变量}} 替换
|
||
$html = PdfHelper::loadTemplate($tpl, [
|
||
'title' => '备货单',
|
||
'order_no' => 'SO' . date('YmdHis'),
|
||
'customer' => 'Magic Bridge Auto FZE',
|
||
]);
|
||
|
||
$driver = new MpdfDriver();
|
||
$pdf = $driver->htmlToPdf($html, [
|
||
// 若 HTML 里用到相对资源(img/css),给个基准目录
|
||
'asset_base' => public_path('assets/pdf'),
|
||
// 也可以单独传 CSS 文件(推荐把 CSS 放在 public/assets/pdf)
|
||
'css_files' => [
|
||
public_path('assets/pdf/stock-order.css'),
|
||
],
|
||
'header_html' => '<div style="text-align:right;color:#888;font-size:10px">Company • Stock Order</div>',
|
||
'footer_html' => '<div style="text-align:center;color:#888;font-size:10px">{PAGENO} / {nbpg}</div>',
|
||
'watermark_text' => '', // 'DRAFT'
|
||
]);
|
||
|
||
return new Response(200, [
|
||
'Content-Type' => 'application/pdf',
|
||
'Content-Disposition' => 'inline; filename="stock-order.pdf"',
|
||
], $pdf);
|
||
}
|
||
|
||
// ② 直接下载
|
||
public function download(Request $request): Response
|
||
{
|
||
$html = '<h1>发票</h1><p>客户:永生花</p>';
|
||
$pdf = (new MpdfDriver())->htmlToPdf($html);
|
||
return new Response(200, [
|
||
'Content-Type' => 'application/pdf',
|
||
'Content-Disposition' => 'attachment; filename="invoice.pdf"',
|
||
], $pdf);
|
||
}
|
||
|
||
// ③ 保存到本地(或上传 OSS 前先落盘)
|
||
public function save(Request $request): Response
|
||
{
|
||
$tpl = base_path('resource/templates/invoice.html');
|
||
$html = PdfHelper::loadTemplate($tpl, [
|
||
'invoice_no' => 'INV' . date('YmdHis'),
|
||
'amount' => '12345.67',
|
||
]);
|
||
|
||
$pdf = (new MpdfDriver())->htmlToPdf($html, [
|
||
'css_files' => [ public_path('assets/pdf/invoice.css') ],
|
||
'asset_base'=> public_path('assets/pdf'),
|
||
]);
|
||
|
||
$dir = runtime_path('pdf');
|
||
if (!is_dir($dir)) mkdir($dir, 0777, true);
|
||
$path = $dir . '/invoice-' . date('YmdHis') . '.pdf';
|
||
file_put_contents($path, $pdf);
|
||
|
||
return json(['path' => $path]);
|
||
}
|
||
}
|