1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types = 1); |
4
|
|
|
|
5
|
|
|
namespace iio\libmergepdf\Driver; |
6
|
|
|
|
7
|
|
|
use iio\libmergepdf\Exception; |
8
|
|
|
use iio\libmergepdf\Source\SourceInterface; |
9
|
|
|
use setasign\Fpdi\Fpdi as FpdiFpdf; |
10
|
|
|
use setasign\Fpdi\Tcpdf\Fpdi as FpdiTcpdf; |
11
|
|
|
use setasign\Fpdi\PdfParser\StreamReader; |
12
|
|
|
|
13
|
|
|
final class Fpdi2Driver implements DriverInterface |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* @var FpdiFpdf|FpdiTcpdf |
17
|
|
|
*/ |
18
|
|
|
private $fpdi; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @param FpdiFpdf|FpdiTcpdf $fpdi |
22
|
|
|
*/ |
23
|
|
|
public function __construct($fpdi = null) |
24
|
|
|
{ |
25
|
|
|
// Tcpdf generates warnings due to argument ordering with php 8 |
26
|
|
|
// suppressing errors is a dirty hack until tcpdf is patched |
27
|
|
|
$this->fpdi = $fpdi ?: @new FpdiTcpdf; |
28
|
|
|
|
29
|
|
|
if (!($this->fpdi instanceof FpdiFpdf) && !($this->fpdi instanceof FpdiTcpdf)) { |
30
|
|
|
throw new \InvalidArgumentException('Constructor argument must be an FPDI instance.'); |
31
|
|
|
} |
32
|
|
|
} |
33
|
|
|
|
34
|
|
View Code Duplication |
public function merge(SourceInterface ...$sources): string |
|
|
|
|
35
|
|
|
{ |
36
|
|
|
$sourceName = ''; |
37
|
|
|
|
38
|
|
|
try { |
39
|
|
|
$fpdi = clone $this->fpdi; |
40
|
|
|
|
41
|
|
|
foreach ($sources as $source) { |
42
|
|
|
$sourceName = $source->getName(); |
43
|
|
|
$pageCount = $fpdi->setSourceFile(StreamReader::createByString($source->getContents())); |
44
|
|
|
$pageNumbers = $source->getPages()->getPageNumbers() ?: range(1, $pageCount); |
45
|
|
|
|
46
|
|
|
foreach ($pageNumbers as $pageNr) { |
47
|
|
|
$template = $fpdi->importPage($pageNr); |
48
|
|
|
$size = $fpdi->getTemplateSize($template); |
49
|
|
|
$fpdi->SetPrintHeader(false); |
50
|
|
|
$fpdi->SetPrintFooter(false); |
51
|
|
|
$fpdi->AddPage( |
|
|
|
|
52
|
|
|
$size['width'] > $size['height'] ? 'L' : 'P', |
53
|
|
|
[$size['width'], $size['height']] |
54
|
|
|
); |
55
|
|
|
$fpdi->useTemplate($template); |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
return $fpdi->Output('', 'S'); |
60
|
|
|
} catch (\Exception $e) { |
61
|
|
|
throw new Exception("'{$e->getMessage()}' in '$sourceName'", 0, $e); |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.