config = $config; $this->mpdf = $mpdf; } public function getTemplatePath(): ?string { if (!isset($this->templatePath)) { $template_path = $this->config->get('report.template_path', FALSE); if (!$template_path) { $template_path = readline('Enter template file path: '); } if (!file_exists($template_path)) { throw new Exception('Template file not found!'); } $this->templatePath = $template_path; } return $this->templatePath; } public function setTemplatePath(string $path): void { if (file_exists($path)) { $this->templatePath = $path; return; } throw new Exception('Template file not found!'); } public function parsedDataToHtmlTable(array $data): ?string { $table = ''; $header = array_shift($data); foreach ($header as $cell) { $table .= ""; } $table .= ''; foreach ($data as $row) { $cells = []; foreach ($row as $cell) { $cells[] = ""; } $rows[] = '' . implode($cells) . ''; } $table .= implode('', $rows); $table .= '
{$cell}
{$cell}
'; return $table; } public function replaceTokensInTemplate(string $template_path, array $tokens): ?string { $template = file_get_contents($template_path); foreach ($tokens as $key => $value) { $template = str_replace("[[{$key}]]", $value, $template); } return $template; } public function pdfExport(string $html, $output = null): bool { $this->mpdf->SetProtection(array('print')); $this->mpdf->SetTitle("Acme Trading Co. - Invoice"); $this->mpdf->SetAuthor("Acme Trading Co."); $this->mpdf->SetDisplayMode('fullpage'); $this->mpdf->WriteHTML($html); if (!$this->output) { $this->output = $this->config->get('report.output', NULL) ?? readline('Enter output file path: '); } $this->mpdf->Output($this->output, Destination::FILE); return file_exists($this->output); } public function setOutput(string $path) { $this->output = $path; } public function fromDataToPdf(array $data, array $tokens = []): bool { $template_path = $this->getTemplatePath(); $tokens['table'] = $this->parsedDataToHtmlTable($data); $html = $this->replaceTokensInTemplate($template_path, $tokens); $success = $this->pdfExport($html); return $success; } }