dolibarr 24.0.0-beta
download_pdf.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2026 Nick Fragoulis
3 * Copyright (C) 2026 MDW <mdeweerd@users.noreply.github.com>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY, without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 */
18
25if (!defined('NOTOKENRENEWAL')) {
26 define('NOTOKENRENEWAL', 1);
27}
28if (!defined('NOCSRFCHECK')) { // TODO Enable the CSRF check
29 define('NOCSRFCHECK', 1);
30}
31
32require '../../main.inc.php';
33require_once DOL_DOCUMENT_ROOT . '/core/lib/pdf.lib.php';
34require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
35require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php';
36require_once DOL_DOCUMENT_ROOT . '/includes/tecnickcom/tcpdf/tcpdf.php';
37
38// Security check
39if (!isModEnabled('ai') || !getDolGlobalString('AI_ASSISTANT_ENABLED')) {
40 accessforbidden('Module or feature not allowed');
41}
42
43global $user, $langs;
44$langs->loadLangs(array('products', 'stocks', 'suppliers', 'companies', 'margins', 'reports@reports'));
45
46// Input validation and sanitization
47$json = GETPOST('data', 'restricthtml');
48if (empty($json)) {
49 $json = file_get_contents('php://input');
50}
51
52// Validate JSON structure
53$data = json_decode($json, true);
54if (json_last_error() !== JSON_ERROR_NONE) {
55 dol_syslog("Invalid JSON data in PDF generation: " . json_last_error_msg(), LOG_ERR);
56 print "Error: Invalid data format provided.";
57 exit;
58}
59
60// Get title and filename
61$title = GETPOST('title', 'restricthtml');
62if (empty($title)) {
63 $title = "AI Report";
64}
65
66$filename = GETPOST('filename', 'restricthtml');
67if (empty($filename)) {
68 $filename = 'Report.pdf';
69}
70
71// Remove control characters and special filesystem characters
72$filename = preg_replace('/[\x00-\x1F\x7F\/\\:*?"<>|]/', '', $filename);
73// Ensure filename has .pdf extension
74if (!preg_match('/\.pdf$/i', $filename)) {
75 $filename .= '.pdf';
76}
77
78if (!$data) {
79 print "No data provided for PDF generation.";
80 exit;
81}
82
83try {
84 $outputlangs = $langs;
85
86 // Get format - use landscape orientation for better column display
87 $format = pdf_getFormat($outputlangs);
88
89 $pdf_dimensions = [$format['width'], $format['height']];
90 $pdf = pdf_getInstance($pdf_dimensions, $format['unit'], 'l');
91 $default_font_size = pdf_getPDFFontSize($outputlangs);
92 $pdf->SetCreator("Dolibarr AI");
93 $pdf->SetAuthor($user->getFullName($langs));
94
95 $pdf->SetTitle($title);
96 $pdf->SetMargins(15, 15, 15);
97 $pdf->SetAutoPageBreak(true, 15);
98 if (class_exists('TCPDF')) {
99 $pdf->setPrintHeader(false);
100 $pdf->setPrintFooter(false);
101 }
102 $pdf->AddPage();
103 $pdf->SetFont('dejavusans', '', 10); // Important for non-Latin languages
104
105 // Header
106 $pdf->SetFont('', 'B', 16);
107 $pdf->Cell(0, 10, $title, 0, 1, 'C');
108 $pdf->SetFont('', '', 9);
109 $pdf->SetTextColor(100, 100, 100);
110 $pdf->Cell(0, 5, dol_print_date(dol_now(), 'dayhour', 'tzuser'), 0, 1, 'R');
111 $pdf->Ln(5);
112 $pdf->SetTextColor(0, 0, 0);
113
114 $html = '<style>
115 h3 { color: #333; border-bottom: 1px solid #ccc; font-size: 12pt; margin-top: 15px; }
116 table { width: 100%; border-collapse: collapse; }
117 th { background-color: #f0f0f0; font-weight: bold; padding: 5px; border: 1px solid #ccc; }
118 td { padding: 5px; border: 1px solid #ccc; }
119 .key { font-weight: bold; width: 30%; background-color: #f9f9f9; }
120 .val { width: 70%; }
121 </style>';
122
123 // Overview / Dashboard (complex object)
124 if (isset($data['customer']) && isset($data['details'])) {
125 // Customer Info
126 $html .= '<h3>' . $langs->trans('ThirdpartyDetails') . '</h3>';
127 $html .= '<table cellpadding="4">';
128 foreach ($data['customer'] as $k => $v) {
129 // Skip internal fields
130 if ($k === 'url' || $k === 'id' || $k === 'rowid') {
131 continue;
132 }
133 $html .= '<tr><td class="key">' . dol_escape_htmltag(ucfirst($k)) . '</td><td class="val">' . dol_escape_htmltag($v) . '</td></tr>';
134 }
135 $html .= '</table>';
136
137 // Sections (Invoices, Orders, etc)
138 foreach ($data['details'] as $section => $rows) {
139 $sectionTitle = dol_escape_htmltag(ucwords((string) str_replace('_', ' ', $section)));
140 $html .= '<h3>' . $sectionTitle . '</h3>';
141
142 if (empty($rows) || !is_array($rows)) {
143 $html .= '<p>' . $langs->trans('NoDataAvailable') . '</p>';
144 } else {
145 // Table Builder for List
146 $keys = array_keys($rows[0]);
147 $keys = array_filter(
148 $keys,
152 static function (string $k) {
153 return $k !== 'url' && $k !== 'rowid';
154 }
155 );
156
157 $html .= '<table cellpadding="4"><thead><tr>';
158 foreach ($keys as $k) {
159 $html .= '<th>' . dol_escape_htmltag(ucfirst($k)) . '</th>';
160 }
161 $html .= '</tr></thead><tbody>';
162 foreach ($rows as $row) {
163 $html .= '<tr>';
164 foreach ($keys as $k) {
165 $val = isset($row[$k]) ? $row[$k] : '-';
166 if (is_array($val)) {
167 $val = count($val);
168 }
169
170 if (is_string($val) && strpos($val, '<a href') !== false) {
171 $html .= '<td>' . $val . '</td>';
172 } else {
173 $html .= '<td>' . dol_escape_htmltag($val) . '</td>';
174 }
175 }
176 $html .= '</tr>';
177 }
178 $html .= '</tbody></table>';
179 }
180 }
181 } elseif (isset($data[0]) && is_array($data[0])) {
182 // Simple list (e.g. search invoices)
183 $keys = array_keys($data[0]);
184 $keys = array_filter(
185 $keys,
189 static function (string $k) {
190 return $k !== 'url' && $k !== 'rowid';
191 }
192 );
193
194 $html .= '<table cellpadding="4"><thead><tr nobr="true">';
195 foreach ($keys as $key) {
196 $html .= '<th>' . dol_escape_htmltag(strtoupper(str_replace('_', ' ', $key))) . '</th>';
197 }
198 $html .= '</tr></thead><tbody>';
199 foreach ($data as $row) {
200 $html .= '<tr nobr="true">';
201 foreach ($keys as $key) {
202 $val = isset($row[$key]) ? $row[$key] : '';
203 if (is_array($val)) {
204 $val = count($val) . ' items';
205 }
206 if (is_string($val) && strpos($val, '<a href') !== false) {
207 $html .= '<td>' . $val . '</td>';
208 } else {
209 $html .= '<td>' . dol_escape_htmltag($val) . '</td>';
210 }
211 }
212 $html .= '</tr>';
213 }
214 $html .= '</tbody></table>';
215 } else {
216 // Simple object
217 $html .= '<table cellpadding="5">';
218 foreach ($data as $key => $val) {
219 // Skip internal fields
220 if ($key === 'url') {
221 continue;
222 }
223 $valStr = is_array($val) ? json_encode($val) : $val;
224 $html .= '<tr><td class="key">' . dol_escape_htmltag(ucfirst($key)) . '</td><td class="val">' . dol_escape_htmltag($valStr) . '</td></tr>';
225 }
226 $html .= '</table>';
227 }
228
229 $pdf->writeHTML($html, true, false, true, false, '');
230 $pdf->Output($filename, 'D');
231} catch (Exception $e) {
232 dol_syslog("Error generating PDF: " . $e->getMessage(), LOG_ERR);
233 print "PDF Error: Unable to generate PDF. Please contact administrator.";
234 exit;
235}
dol_now($mode='gmt')
Return date for now.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
pdf_getFormat($outputlangs=null, $mode='setup')
Return array with format properties of default PDF format.
Definition pdf.lib.php:87
pdf_getPDFFontSize($outputlangs)
Return font size to use for PDF generation.
Definition pdf.lib.php:294
pdf_getInstance($format='', $metric='mm', $pagetype='P')
Return a PDF instance object.
Definition pdf.lib.php:129
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.