<?php
namespace App\Http\Controllers;
use App\Models\Pdf;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use setasign\Fpdi\Fpdi;
class PdfController extends Controller
{
public function index(){
$pdfs = Pdf::orderBy('sort')->get();
return view('pdf.index', compact('pdfs'));
}
public function upload(Request $request){
$request->validate([
'pdfs.*' => 'required|file|mimes:pdf|max:20480',
]);
foreach ($request->file('pdfs') as $file) {
$path = $file->store('pdfs', 'local');
if (!Storage::disk('local')->exists($path)) {
return back()->with('error', '檔案存檔失敗:' . $file->getClientOriginalName());
}
Pdf::create([
'filename' => $file->getClientOriginalName(),
'path' => $path,
'sort' => Pdf::max('sort') + 1,
]);
}
return back()->with('success', '上傳成功');
}
public function sort(Request $request){
$order = $request->order;
foreach ($order as $index => $id) {
Pdf::where('id', $id)->update(['sort' => $index]);
}
return response()->json(['status' => 'ok']);
}
public function merge(){
$pdfs = Pdf::orderBy('sort')->get();
if ($pdfs->isEmpty()) {
return back()->with('error', '沒有任何 PDF 可合併');
}
$pdf = new Fpdi();
foreach ($pdfs as $item) {
if (!Storage::disk('local')->exists($item->path)) {
return back()->with('error', "檔案不存在:{$item->filename}");
}
$filePath = Storage::disk('local')->path($item->path);
$pageCount = $pdf->setSourceFile($filePath);
for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
$templateId = $pdf->importPage($pageNo);
$size = $pdf->getTemplateSize($templateId);
$pdf->AddPage($size['orientation'], [$size['width'], $size['height']]);
$pdf->useTemplate($templateId);
}
}
$filename = 'merged_' . time() . '.pdf';
return response($pdf->Output('S'))
->header('Content-Type', 'application/pdf')
->header('Content-Disposition', "attachment; filename=\"$filename\"");
}
// ✅ 新增:刪除 PDF
public function destroy($id){
$pdf = Pdf::findOrFail($id);
// 刪除實體檔案
if (Storage::disk('local')->exists($pdf->path)) {
Storage::disk('local')->delete($pdf->path);
}
// 刪除資料庫紀錄
$pdf->delete();
return response()->json(['status' => 'deleted']);
}
}