templatesPath = __DIR__ . '/../../templates/pdf/'; $this->assetsPath = '/var/www/html/data/admin/files/.gestion/'; } public function generatePdf($templateName, $data, $options = []) { try { $htmlContent = $this->renderPhpTemplate($templateName, $data); return $this->convertToPdf($htmlContent, $options); } catch (\Exception $e) { error_log('HtmlToPdfService Error: ' . $e->getMessage()); throw new TemplateException('Erreur génération PDF: ' . $e->getMessage()); } } /** * Rend un template PHP avec les données */ private function renderPhpTemplate($templateName, $data) { $templateFile = $this->templatesPath . $templateName . '.php'; if (!file_exists($templateFile)) { throw new TemplateException("Template introuvable: " . $templateFile); } try { $templateData = array_merge($data, [ 'logo_base64' => $this->getLogoBase64() ]); extract($templateData); ob_start(); include $templateFile; return ob_get_clean(); } catch (Throwable $e) { ob_end_clean(); throw new TemplateException("Erreur lors du rendu du template: " . $e->getMessage(), 0, $e); } } /** * Récupère le logo en base64 */ private function getLogoBase64() { $logoPath = $this->assetsPath . 'logo.png'; if (file_exists($logoPath)) { return base64_encode(file_get_contents($logoPath)); } // Retour d'un pixel transparent si pas de logo return 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=='; } /** * Convertit HTML en PDF */ private function convertToPdf($htmlContent, $options = []) { $dompdfOptions = new Options(); $dompdfOptions->set('defaultFont', 'DejaVu Sans'); $dompdfOptions->set('isRemoteEnabled', true); $dompdfOptions->set('isHtml5ParserEnabled', true); $dompdfOptions->set('enable_css_float', true); $dompdfOptions->set('enable_font_subsetting', true); $paper = $options['paper'] ?? 'A4'; $orientation = $options['orientation'] ?? 'portrait'; $dompdf = new Dompdf($dompdfOptions); $dompdf->loadHtml($htmlContent); $dompdf->setPaper($paper, $orientation); $dompdf->render(); return $dompdf->output(); } public function generateInvoiceFilename($factureData, $prefix = 'FACTURE') { $numero = str_pad($factureData['num'] ?? '', 6, '0', STR_PAD_LEFT); $month = str_pad($factureData['month'] ?? date('m'), 2, '0', STR_PAD_LEFT); $year = $factureData['year'] ?? date('Y'); return "{$prefix}_{$numero}_{$month}_{$year}.pdf"; } /** * Debug template PHP */ public function debugTemplate($templateName, $data) { echo "=== DONNÉES REÇUES ===\n"; var_dump($data); echo "\n=== TEMPLATE PHP UTILISÉ ===\n"; $templateFile = $this->templatesPath . $templateName . '.php'; echo "Fichier: $templateFile\n"; echo "Existe: " . (file_exists($templateFile) ? "OUI" : "NON") . "\n"; echo "\n=== HTML GÉNÉRÉ ===\n"; $html = $this->renderPhpTemplate($templateName, $data); echo substr($html, 0, 2000) . "...\n"; return $html; } }