1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace PhpCfdi\CfdiToPdf\Builders; |
6
|
|
|
|
7
|
|
|
use PhpCfdi\CfdiToPdf\Builders\HtmlTranslators\HtmlTranslatorInterface; |
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
|
|
|
/** @var HtmlTranslators\HtmlTranslatorInterface */ |
16
|
|
|
private $htmlTranslator; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Html2PdfBuilder constructor. |
20
|
|
|
* |
21
|
|
|
* @param HtmlTranslatorInterface|null $htmlTranslator If NULL will use a generic translator |
22
|
|
|
*/ |
23
|
4 |
|
public function __construct(HtmlTranslatorInterface $htmlTranslator = null) |
24
|
|
|
{ |
25
|
4 |
|
if (null === $htmlTranslator) { |
26
|
4 |
|
$htmlTranslator = new HtmlTranslators\PlatesHtmlTranslator( |
27
|
4 |
|
dirname(__DIR__, 2) . '/templates/', // __DIR__ is src/Builders |
28
|
4 |
|
'generic', |
29
|
4 |
|
); |
30
|
|
|
} |
31
|
4 |
|
$this->htmlTranslator = $htmlTranslator; |
32
|
|
|
} |
33
|
|
|
|
34
|
2 |
|
public function build(CfdiData $data, string $destination): void |
35
|
|
|
{ |
36
|
2 |
|
file_put_contents($destination, $this->buildPdf($data)); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Transforms CfdiData to Pdf string |
41
|
|
|
* |
42
|
|
|
* @param CfdiData $data |
43
|
|
|
* @return string |
44
|
|
|
*/ |
45
|
2 |
|
public function buildPdf(CfdiData $data): string |
46
|
|
|
{ |
47
|
2 |
|
$html = $this->convertNodeToHtml($data); |
48
|
2 |
|
$output = $this->convertHtmlToPdf($html); |
49
|
2 |
|
return $output; |
50
|
|
|
} |
51
|
|
|
|
52
|
1 |
|
public function convertHtmlToPdf(string $html): string |
53
|
|
|
{ |
54
|
|
|
// don't do it directly since Html2Pdf::output check that the file extension is pdf |
55
|
|
|
try { |
56
|
1 |
|
$html2Pdf = new Html2Pdf('P', 'Letter', 'es', true, 'UTF-8', [10, 10, 10, 10]); |
57
|
1 |
|
$html2Pdf->writeHTML($html); |
58
|
1 |
|
$output = $html2Pdf->output('', 'S'); |
59
|
1 |
|
return $output; |
60
|
|
|
} catch (Html2PdfException $exception) { |
61
|
|
|
/** @codeCoverageIgnore don't know how to invoke this exception on Html2Pdf */ |
62
|
|
|
throw new RuntimeException('Unable to convert CFDI', 0, $exception); |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
1 |
|
public function convertNodeToHtml(CfdiData $cfdiData): string |
67
|
|
|
{ |
68
|
1 |
|
return $this->htmlTranslator->translate($cfdiData); |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|