« Back to History
print_system.php
|
20260722_120325.php
Initial Domain Snapshot
Copy Code
<?php /** * print_system.php * * Reusable print / PDF / CSV exporter helpers for ERP report pages. * - Contains: PHP helpers to build printable HTML and export PDF (dompdf), * CSV exporter, and a JS function to open a minimal print window and auto-close. * * Usage: * require_once __DIR__.'/print_system.php'; * echo print_button_js(); // output JS once per page (prefer in head) * echo print_button_html(['selector'=>'#reportTable','title'=>'My Report']); * // Or server-side PDF: $html = build_print_html(...); export_pdf_from_html($html,'report.pdf'); * * Keep page-local. Do NOT modify global configs here. */ /* ------------------------- * PHP: Build printable HTML * ------------------------- */ function build_print_html(string $title, string $summary_html, string $table_html, array $opts = []): string { $charset = $opts['charset'] ?? 'utf-8'; $styles = $opts['styles'] ?? " body{font-family:Arial, sans-serif; padding:12px; color:#222} .summary{font-weight:700;margin-bottom:8px} table{width:100%;border-collapse:collapse} th,td{border:1px solid #ddd;padding:6px 8px} thead th{background:#f0f8f0} tfoot td{font-weight:700;background:#fff9e8} "; $html = '<!doctype html><html><head><meta charset="'.htmlspecialchars($charset).'"><title>' .htmlspecialchars($title).'</title><style>'.$styles.'</style></head><body>'; $html .= '<h3>'.htmlspecialchars($title).'</h3>'; $html .= $summary_html; $html .= $table_html; $html .= '</body></html>'; return $html; } /* ----------------------------------------- * PHP: Server-side PDF export using Dompdf * (optional — only if dompdf is installed) * ----------------------------------------- */ function export_pdf_from_html(string $html, string $filename = 'export.pdf', bool $stream = true) { // require dompdf if available $autoload = __DIR__ . '/../vendor/autoload.php'; if (!is_file($autoload)) { throw new RuntimeException("Dompdf autoload not found. Install dompdf/dompdf via composer and place vendor/ next to your app."); } require_once $autoload; if (!class_exists(\Dompdf\Dompdf::class)) { throw new RuntimeException("Dompdf class not found. Ensure dompdf is installed."); } $dompdf = new \Dompdf\Dompdf(); $dompdf->loadHtml($html); $dompdf->setPaper('A4', 'landscape'); $dompdf->render(); if ($stream) { $dompdf->stream($filename, ['Attachment' => 1]); // download exit; } else { return $dompdf->output(); // raw PDF bytes } } /* ------------------------- * PHP: Simple CSV exporter * - $rows: array of associative arrays (same keys) * - provide headers or infer from first row * - outputs CSV and exits * ------------------------- */ function export_csv(array $rows, string $filename = 'export.csv', array $headers = []) { if (empty($rows) && empty($headers)) { throw new InvalidArgumentException("No rows/headers provided for CSV export."); } header('Content-Type: text/csv; charset=utf-8'); header('Content-Disposition: attachment; filename="'.basename($filename).'"'); $out = fopen('php://output', 'w'); // BOM for Excel UTF-8 compatibility fwrite($out, "\xEF\xBB\xBF"); if (empty($headers)) { $headers = array_keys(reset($rows)); } fputcsv($out, $headers); foreach ($rows as $r) { $line = []; foreach ($headers as $h) { $line[] = array_key_exists($h, $r) ? $r[$h] : ''; } fputcsv($out, $line); } fclose($out); exit; } /* ------------------------------------------------ * HTML helper: print button (small reusable snippet) * - $opts: selector (CSS selector for table), title, summarySelector (optional) * ------------------------------------------------ */ function print_button_html(array $opts = []): string { $selector = $opts['selector'] ?? '.print-target-table'; $title = $opts['title'] ?? 'Report'; $btn_text = $opts['btn_text'] ?? 'Print'; $id = 'ps_btn_' . bin2hex(random_bytes(4)); $js = "window.PrintSystem_printFromSelector('".addslashes($selector)."','".addslashes($title)."');"; return '<button class="btn gray" type="button" id="'.htmlspecialchars($id).'" onclick="'.htmlspecialchars($js).'">' .htmlspecialchars($btn_text).'</button>'; } /* ------------------------------------------------ * JS: Print system script (callable from any page) * - include this JS once per page (preferably in <head>) * - call: window.PrintSystem_printFromSelector('#myTable','Title','Summary text html') * ------------------------------------------------ */ function print_button_js(): string { // The function clones the table HTML and summary (optional) into a minimal window, // calls print(), and auto-closes the print window after printing. return <<<JS <script> window.PrintSystem_printFromSelector = function(tableSelector, title, summaryHtml){ try { var tableEl = document.querySelector(tableSelector); if(!tableEl){ alert('Print target not found: ' + tableSelector); return; } var w = window.open('', '_blank', 'toolbar=0,location=0,menubar=0,width=1000,height=700'); var doc = w.document; doc.open(); var styles = "body{font-family:Arial, sans-serif; padding:12px; color:#222} .summary{font-weight:700;margin-bottom:8px} table{width:100%;border-collapse:collapse} th,td{border:1px solid #ddd;padding:6px 8px} thead th{background:#f0f8f0} tfoot td{font-weight:700;background:#fff9e8}"; doc.write('<!doctype html><html><head><meta charset=\"utf-8\"><title>'+ (title||'Print') +'</title><style>'+styles+'</style></head><body>'); doc.write('<h3>'+ (title||'Report') +'</h3>'); if (typeof summaryHtml !== 'undefined' && summaryHtml !== null) { doc.write('<div class=\"summary\">'+ summaryHtml +'</div>'); } // clone table DOM to preserve innerHTML (but avoid copying IDs) var tclone = tableEl.cloneNode(true); // remove id attributes (avoid duplicates) var nodes = tclone.querySelectorAll('[id]'); for(var i=0;i<nodes.length;i++){ nodes[i].removeAttribute('id'); } doc.write(tclone.outerHTML); // onafterprint: close window; add timeout to ensure print dialog finishes doc.write('<script>function finish(){ try{ window.onafterprint=null; window.close(); }catch(e){} } window.onafterprint = finish; setTimeout(function(){ window.print(); setTimeout(finish,500); },150);<\/script>'); doc.write('</body></html>'); doc.close(); w.focus(); } catch (err) { console.error('PrintSystem error', err); alert('Printing failed: ' + (err && err.message ? err.message : 'unknown')); } }; </script> JS; } ?>