AuditExpress_PDF.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /**
  3. * Snippet : AuditExpress_PDF
  4. * Génère et télécharge le PDF à la demande (depuis la page résultats, bouton "Télécharger").
  5. *
  6. * Appelé en mode uncached via un lien direct :
  7. * /audit-express/pdf/?audit=<uid>
  8. * ou via une ressource dédiée avec ce snippet.
  9. *
  10. * Propriétés :
  11. * &booking_url = `https://calendly.com/livinweb/diagnostic`
  12. *
  13. * Envoie directement les headers PDF + contenu binaire, puis exit.
  14. */
  15. declare(strict_types=1);
  16. $corePath = $modx->getOption('ae.core_path', null,
  17. $modx->getOption('core_path') . 'components/audit_express/');
  18. $modx->addPackage('audit_express', $corePath . 'model/');
  19. require_once $corePath . 'src/PackRepository.php';
  20. require_once $corePath . 'src/PdfRenderer.php';
  21. $bookingUrl = $scriptProperties['booking_url'] ?? $modx->getOption('ae.booking_url', null, '');
  22. $auditUid = trim($_GET['audit'] ?? '');
  23. if (!$auditUid) {
  24. http_response_code(400);
  25. echo json_encode(['error' => 'audit_uid manquant']);
  26. return '';
  27. }
  28. /** @var AuditRequest|null $auditReq */
  29. $auditReq = $modx->getObject('AuditRequest', ['audit_uid' => $auditUid]);
  30. if (!$auditReq || $auditReq->get('status') === 'draft') {
  31. http_response_code(404);
  32. echo json_encode(['error' => 'Audit non trouvé ou non terminé']);
  33. return '';
  34. }
  35. try {
  36. $packId = $auditReq->get('pack_id');
  37. $repo = new \AuditExpress\PackRepository($corePath . 'config/');
  38. $pack = $repo->getPack($packId);
  39. $result = $auditReq->getResultArray();
  40. $renderer = new \AuditExpress\PdfRenderer(
  41. $corePath . 'templates/pdf_a4.php',
  42. $corePath . '../vendor/autoload.php'
  43. );
  44. $pdfBytes = $renderer->render($pack, $result, $bookingUrl);
  45. $filename = 'controle-technique-' . preg_replace('/[^a-z0-9\-]/', '', $packId) . '.pdf';
  46. header('Content-Type: application/pdf');
  47. header('Content-Disposition: attachment; filename="' . $filename . '"');
  48. header('Content-Length: ' . strlen($pdfBytes));
  49. header('Cache-Control: no-store');
  50. echo $pdfBytes;
  51. exit;
  52. } catch (\Throwable $e) {
  53. http_response_code(500);
  54. $modx->log(xPDO::LOG_LEVEL_ERROR, '[AuditExpress] PDF: ' . $e->getMessage());
  55. echo json_encode(['error' => 'Erreur génération PDF']);
  56. return '';
  57. }