1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace PhpCfdi\CfdiToPdf\Builders; |
6
|
|
|
|
7
|
|
|
use League\Plates\Engine as PlatesEngine; |
8
|
|
|
use PhpCfdi\CfdiToPdf\CfdiData; |
9
|
|
|
use RuntimeException; |
10
|
|
|
use Spipu\Html2Pdf\Exception\Html2PdfException; |
11
|
|
|
use Spipu\Html2Pdf\Html2Pdf; |
12
|
|
|
|
13
|
|
|
class Html2PdfBuilder implements BuilderInterface |
14
|
|
|
{ |
15
|
2 |
|
public function build(CfdiData $data, string $destination) |
16
|
|
|
{ |
17
|
2 |
|
file_put_contents($destination, $this->buildPdf($data)); |
18
|
2 |
|
} |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* Transforms CfdiData to Pdf string |
22
|
|
|
* |
23
|
|
|
* @param CfdiData $data |
24
|
|
|
* @return string |
25
|
|
|
*/ |
26
|
2 |
|
public function buildPdf(CfdiData $data): string |
27
|
|
|
{ |
28
|
2 |
|
$html = $this->convertNodeToHtml($data); |
29
|
2 |
|
$output = $this->convertHtmlToPdf($html); |
30
|
2 |
|
return $output; |
31
|
|
|
} |
32
|
|
|
|
33
|
1 |
|
public function convertHtmlToPdf(string $html): string |
34
|
|
|
{ |
35
|
|
|
// don't do it directly since Html2Pdf::output check that the file extension is pdf |
36
|
|
|
try { |
37
|
1 |
|
$html2Pdf = new Html2Pdf('P', 'Letter', 'es', true, 'UTF-8', [10, 10, 10, 10]); |
38
|
1 |
|
$html2Pdf->writeHTML($html); |
39
|
1 |
|
$output = $html2Pdf->output('', 'S'); |
40
|
1 |
|
return $output; |
41
|
|
|
} catch (Html2PdfException $exception) { |
42
|
|
|
/** @codeCoverageIgnore don't know how to invoke this exception on Html2Pdf */ |
43
|
|
|
throw new RuntimeException('Unable to convert CFDI', 0, $exception); |
44
|
|
|
} |
45
|
|
|
} |
46
|
|
|
|
47
|
1 |
|
public function convertNodeToHtml(CfdiData $cfdiData): string |
48
|
|
|
{ |
49
|
|
|
// __DIR__ is src/Builders |
50
|
1 |
|
$plates = new PlatesEngine(dirname(__DIR__, 2) . '/templates/'); |
51
|
1 |
|
return $plates->render('generic', ['cfdiData' => $cfdiData]); |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
|