QRFpdf.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. <?php
  2. /**
  3. * Class QRFpdf
  4. *
  5. * @created 03.06.2020
  6. * @author Maximilian Kresse
  7. * @license MIT
  8. *
  9. * @see https://github.com/chillerlan/php-qrcode/pull/49
  10. */
  11. namespace chillerlan\QRCode\Output;
  12. use chillerlan\QRCode\Data\QRMatrix;
  13. use chillerlan\QRCode\QRCodeException;
  14. use chillerlan\Settings\SettingsContainerInterface;
  15. use FPDF;
  16. use function array_values, class_exists, count, is_array;
  17. /**
  18. * QRFpdf output module (requires fpdf)
  19. *
  20. * @see https://github.com/Setasign/FPDF
  21. * @see http://www.fpdf.org/
  22. */
  23. class QRFpdf extends QROutputAbstract{
  24. public function __construct(SettingsContainerInterface $options, QRMatrix $matrix){
  25. if(!class_exists(FPDF::class)){
  26. // @codeCoverageIgnoreStart
  27. throw new QRCodeException(
  28. 'The QRFpdf output requires FPDF as dependency but the class "\FPDF" couldn\'t be found.'
  29. );
  30. // @codeCoverageIgnoreEnd
  31. }
  32. parent::__construct($options, $matrix);
  33. }
  34. /**
  35. * @inheritDoc
  36. */
  37. protected function setModuleValues():void{
  38. foreach($this::DEFAULT_MODULE_VALUES as $M_TYPE => $defaultValue){
  39. $v = $this->options->moduleValues[$M_TYPE] ?? null;
  40. if(!is_array($v) || count($v) < 3){
  41. $this->moduleValues[$M_TYPE] = $defaultValue
  42. ? [0, 0, 0]
  43. : [255, 255, 255];
  44. }
  45. else{
  46. $this->moduleValues[$M_TYPE] = array_values($v);
  47. }
  48. }
  49. }
  50. /**
  51. * @inheritDoc
  52. *
  53. * @return string|\FPDF
  54. */
  55. public function dump(string $file = null){
  56. $file ??= $this->options->cachefile;
  57. $fpdf = new FPDF('P', $this->options->fpdfMeasureUnit, [$this->length, $this->length]);
  58. $fpdf->AddPage();
  59. $prevColor = null;
  60. foreach($this->matrix->matrix() as $y => $row){
  61. foreach($row as $x => $M_TYPE){
  62. /** @var int $M_TYPE */
  63. $color = $this->moduleValues[$M_TYPE];
  64. if($prevColor === null || $prevColor !== $color){
  65. /** @phan-suppress-next-line PhanParamTooFewUnpack */
  66. $fpdf->SetFillColor(...$color);
  67. $prevColor = $color;
  68. }
  69. $fpdf->Rect($x * $this->scale, $y * $this->scale, 1 * $this->scale, 1 * $this->scale, 'F');
  70. }
  71. }
  72. if($this->options->returnResource){
  73. return $fpdf;
  74. }
  75. $pdfData = $fpdf->Output('S');
  76. if($file !== null){
  77. $this->saveToFile($pdfData, $file);
  78. }
  79. if($this->options->imageBase64){
  80. $pdfData = $this->base64encode($pdfData, 'application/pdf');
  81. }
  82. return $pdfData;
  83. }
  84. }