Generowanie pdf-a z pdf-a - biały ekran

Generowanie pdf-a z pdf-a - biały ekran
KI
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 83
0

Dzień dobry,

Mam napisany program w Laravelu, jednym z jego zadań jest generowanie zaproszeń.
Problem mianowicie wygląda następująco.
Jeżeli do programu wrzucę Worda z polami w ${Imie i nazwisko} i zrobię programowego save as to robi mi poprawnie worda z danymi z bazy.

Jeżeli, chce zrobić save do pdf-a to dostaję biały ekran.
Może ma ktoś gotowca na w raz z instrukcją jak zrobić pdf to pdf.

Bardzo wam dziekuję.

Kopiuj
<?php

namespace App\Http\Controllers;

use App\Models\Event;
use App\Models\Guest;
use App\Models\Seat;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
use PhpOffice\PhpWord\TemplateProcessor;
use ZipArchive;
use Illuminate\Support\Str;

class BadgeController extends Controller
{
    public function generateBadge(Event $event, Seat $seat)
    {
        // Sprawdź, czy miejsce należy do tego wydarzenia
        if ($seat->event_id !== $event->id) {
            abort(404);
        }

        // Sprawdź, czy miejsce ma przypisanego gościa
        if (!$seat->guest_id) {
            return redirect()->back()->with('error', 'To miejsce nie ma przypisanego gościa.');
        }

        $guest = $seat->guest;

        // Sprawdź, czy wydarzenie ma szablon DOCX identyfikatora
        $templateDocxPath = str_replace('.pdf', '.docx', $event->badge_template_path ?? '');
        if (!Storage::disk('public')->exists($templateDocxPath)) {
            return redirect()->back()->with('error', 'Brak szablonu DOCX identyfikatora dla tego wydarzenia.');
        }

        // Ścieżka do szablonu DOCX
        $templatePath = storage_path('app/public/' . $templateDocxPath);

        // Generowanie kodu QR
        $qrPath = null;
        if ($guest->qr_code) {
            // Generowanie kodu QR i zapisanie do pliku
            $qrCode = QrCode::format('png')
                ->size(200)
                ->margin(0)
                ->generate($guest->qr_code);

            $qrFilename = 'qr_' . $guest->id . '_' . uniqid() . '.png';
            $qrPath = storage_path('app/public/temp/' . $qrFilename);
            
            Storage::makeDirectory('public/temp');
            file_put_contents($qrPath, $qrCode);
        }

        try {
            // Utwórz procesor szablonu Word
            $templateProcessor = new TemplateProcessor($templatePath);
            
            // Podmień znaczniki w szablonie
            $templateProcessor->setValue('Imie i Nazwisko', $guest->full_name);
            $templateProcessor->setValue('Rola', $seat->role ? $seat->role->name : '');
            
            // Jeśli jest kod QR, zamień go
            if ($qrPath) {
                $templateProcessor->setImageValue('QR', [
                    'path' => $qrPath,
                    'width' => 75,
                    'height' => 75,
                    'ratio' => false
                ]);
            }
            
            // Tworzenie bezpiecznej nazwy pliku (usunięcie znaków specjalnych)
            $safeEventName = Str::slug($event->name);
            $safeGuestName = Str::slug($guest->full_name);
            
            // Zapisz zmodyfikowany dokument do pliku tymczasowego
            $tempDocxPath = storage_path('app/public/temp/identyfikator_' . $safeEventName . '_' . $safeGuestName . '_' . uniqid() . '.docx');
            $templateProcessor->saveAs($tempDocxPath);
            
            // Przeczytaj wygenerowany dokument Word i wyślij do przeglądarki
            $docx = file_get_contents($tempDocxPath);
            
            // Usuń pliki tymczasowe
            @unlink($tempDocxPath);
            if ($qrPath && file_exists($qrPath)) {
                @unlink($qrPath);
            }
            
            $filename = 'identyfikator_' . $safeEventName . '_' . $safeGuestName . '.docx';
            
            return response($docx)
                ->header('Content-Type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document')
                ->header('Content-Disposition', 'inline; filename="' . $filename . '"');
        } catch (\Exception $e) {
            // Usuń pliki tymczasowe w przypadku błędu
            @unlink($tempDocxPath ?? '');
            if ($qrPath && file_exists($qrPath)) {
                @unlink($qrPath);
            }
            
            // Obsługa błędu
            return redirect()->back()->with('error', 'Wystąpił błąd podczas generowania identyfikatora: ' . $e->getMessage());
        }
    }

    public function generateAllBadges(Event $event)
    {
        // Sprawdź, czy wydarzenie ma szablon DOCX identyfikatora
        $templateDocxPath = str_replace('.pdf', '.docx', $event->badge_template_path ?? '');
        if (!Storage::disk('public')->exists($templateDocxPath)) {
            return redirect()->back()->with('error', 'Brak szablonu DOCX identyfikatora dla tego wydarzenia.');
        }

        // Pobierz wszystkie miejsca z przypisanymi gośćmi
        $seats = $event->seats()->whereNotNull('guest_id')->with('guest', 'role')->get();

        if ($seats->isEmpty()) {
            return redirect()->back()->with('error', 'Brak przypisanych gości do miejsc w tym wydarzeniu.');
        }

        try {
            // Przygotuj katalog tymczasowy
            $tempDir = storage_path('app/public/temp/batch_' . uniqid());
            if (!file_exists($tempDir)) {
                mkdir($tempDir, 0777, true);
            }
            
            $docxFiles = [];
            
            foreach ($seats as $seat) {
                $guest = $seat->guest;
                
                // Tworzenie bezpiecznej nazwy pliku
                $safeEventName = Str::slug($event->name);
                $safeGuestName = Str::slug($guest->full_name);
                
                // Generowanie kodu QR
                $qrPath = null;
                if ($guest->qr_code) {
                    // Generowanie kodu QR i zapisanie do pliku
                    $qrCode = QrCode::format('png')
                        ->size(200)
                        ->margin(0)
                        ->generate($guest->qr_code);

                    $qrFilename = 'qr_' . $safeGuestName . '_' . uniqid() . '.png';
                    $qrPath = $tempDir . '/' . $qrFilename;
                    file_put_contents($qrPath, $qrCode);
                }
                
                // Utwórz procesor szablonu Word
                $templatePath = storage_path('app/public/' . $templateDocxPath);
                $templateProcessor = new TemplateProcessor($templatePath);
                
                // Podmień znaczniki w szablonie - dostosuj nazwy do tych, które są w dokumencie
                $templateProcessor->setValue('Imie i Nazwisko', $guest->full_name);
                $templateProcessor->setValue('Rola', $seat->role ? $seat->role->name : '');
                
                // Jeśli jest kod QR, zamień go
                if ($qrPath) {
                    // Dodaj obraz QR kodu do dokumentu
                    $templateProcessor->setImageValue('QR', [
                        'path' => $qrPath,
                        'width' => 75,
                        'height' => 75,
                        'ratio' => false
                    ]);
                }
                
                // Nazwa pliku z informacjami o wydarzeniu i gościu
                $docxFilename = 'identyfikator_' . $safeEventName . '_' . $safeGuestName . '.docx';
                
                // Zapisz zmodyfikowany dokument do pliku tymczasowego
                $tempDocxPath = $tempDir . '/' . $docxFilename;
                $templateProcessor->saveAs($tempDocxPath);
                
                $docxFiles[] = [
                    'path' => $tempDocxPath,
                    'name' => $docxFilename
                ];
                
                // Usuń niepotrzebne pliki
                if ($qrPath && file_exists($qrPath)) {
                    @unlink($qrPath);
                }
            }
            
            // Stwórz archiwum ZIP z wszystkimi dokumentami Word
            $safeEventName = Str::slug($event->name);
            $zipFilename = 'identyfikatory_' . $safeEventName . '.zip';
            $zipPath = $tempDir . '/' . $zipFilename;
            
            $zip = new ZipArchive();
            if ($zip->open($zipPath, ZipArchive::CREATE) === TRUE) {
                foreach ($docxFiles as $file) {
                    $zip->addFile($file['path'], $file['name']);
                }
                $zip->close();
            } else {
                throw new \Exception('Nie można utworzyć archiwum ZIP');
            }
            
            // Przeczytaj archiwum ZIP
            $zipContent = file_get_contents($zipPath);
            
            // Usuń wszystkie pliki tymczasowe
            foreach ($docxFiles as $file) {
                @unlink($file['path']);
            }
            @unlink($zipPath);
            @rmdir($tempDir);
            
            return response($zipContent)
                ->header('Content-Type', 'application/zip')
                ->header('Content-Disposition', 'attachment; filename="' . $zipFilename . '"');
        } catch (\Exception $e) {
            // Usuń wszystkie pliki tymczasowe w przypadku błędu
            if (isset($tempDir) && file_exists($tempDir)) {
                $files = glob($tempDir . '/*');
                foreach ($files as $file) {
                    @unlink($file);
                }
                @rmdir($tempDir);
            }

            return redirect()->back()->with('error', 'Wystąpił błąd podczas generowania identyfikatorów: ' . $e->getMessage());
        }
    }
    
    /**
     * Zapisuje kod QR do pliku
     */
    public function saveQrCode(Guest $guest)
    {
        if (!$guest->qr_code) {
            return redirect()->back()->with('error', 'Ten gość nie ma wygenerowanego kodu QR.');
        }
        
        // Generowanie kodu QR
        $qrCode = QrCode::format('png')
            ->size(500)
            ->margin(2)
            ->generate($guest->qr_code);
        
        // Utwórz bezpieczną nazwę pliku
        $safeGuestName = Str::slug($guest->full_name);
        $filename = 'qr_kod_' . $safeGuestName . '.png';
        
        return response($qrCode)
            ->header('Content-Type', 'image/png')
            ->header('Content-Disposition', 'attachment; filename="' . $filename . '"');
    }
    
    /**
     * Logowanie skanowania kodu QR
     */
    public function scanLog(Request $request)
    {
        $qrCode = $request->input('qr_code');
        $guest = Guest::where('qr_code', $qrCode)->first();
        
        if (!$guest) {
            return response()->json([
                'status' => 'error',
                'message' => 'Nieprawidłowy kod QR'
            ], 404);
        }
        
        // Zapisz log skanowania
        $guest->scan_logs()->create([
            'scanned_at' => now(),
            'device_info' => $request->userAgent()
        ]);
        
        return response()->json([
            'status' => 'success',
            'guest' => [
                'id' => $guest->id,
                'full_name' => $guest->full_name,
                'has_access' => $guest->has_access
            ]
        ]);
    }
}
LA
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 3
0

Najprościej będzie jak zapiszesz dox w jakimś tymczasowym atalogu, a potem odpalisz jakiś konwerter i zmienisz na PDF. ewentualnie wstaw to do kolejki i uzytkownikowi pokaz jakiś loader ze generujesz plik, i potem odczytujesz pdf i wyswietlasz go czytam dajesz do ściagniecia

Kopiuj
$pdf = file_get_contents($tymczasowy_katalog/plik.pdf);
return response($pdf)
    ->header('Content-Type', 'application/pdf')
    ->header('Content-Disposition', 'inline; filename="nazwa_docelowa_pliku.pdf"');

Zarejestruj się i dołącz do największej społeczności programistów w Polsce.

Otrzymaj wsparcie, dziel się wiedzą i rozwijaj swoje umiejętności z najlepszymi.