Completed
Push — master ( 2db788...28adc0 )
by Freek
02:03
created

Pdf::setLayerMethod()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
c 0
b 0
f 0
rs 9.4285
cc 3
eloc 6
nc 2
nop 1
1
<?php
2
3
namespace Spatie\PdfToImage;
4
5
use Spatie\PdfToImage\Exceptions\InvalidFormat;
6
use Spatie\PdfToImage\Exceptions\PdfDoesNotExist;
7
use Spatie\PdfToImage\Exceptions\PageDoesNotExist;
8
use Spatie\PdfToImage\Exceptions\InvalidLayerMethod;
9
10
class Pdf
11
{
12
    protected $pdfFile;
13
14
    protected $resolution = 144;
15
16
    protected $outputFormat = 'jpg';
17
18
    protected $page = 1;
19
20
    protected $imagick;
21
22
    protected $validOutputFormats = ['jpg', 'jpeg', 'png'];
23
24
    protected $layerMethod = \Imagick::LAYERMETHOD_FLATTEN;
25
26
    /**
27
     * @param string $pdfFile The path or url to the pdffile.
28
     *
29
     * @throws \Spatie\PdfToImage\Exceptions\PdfDoesNotExist
30
     */
31
    public function __construct($pdfFile)
32
    {
33
        if (! filter_var($pdfFile, FILTER_VALIDATE_URL) && ! file_exists($pdfFile)) {
34
            throw new PdfDoesNotExist();
35
        }
36
37
        $this->imagick = new \Imagick($pdfFile);
38
        $this->pdfFile = $pdfFile;
39
    }
40
41
    /**
42
     * Set the raster resolution.
43
     *
44
     * @param int $resolution
45
     *
46
     * @return $this
47
     */
48
    public function setResolution($resolution)
49
    {
50
        $this->resolution = $resolution;
51
52
        return $this;
53
    }
54
55
    /**
56
     * Set the output format.
57
     *
58
     * @param string $outputFormat
59
     *
60
     * @return $this
61
     *
62
     * @throws \Spatie\PdfToImage\Exceptions\InvalidFormat
63
     */
64
    public function setOutputFormat($outputFormat)
65
    {
66
        if (! $this->isValidOutputFormat($outputFormat)) {
67
            throw new InvalidFormat('Format '.$outputFormat.' is not supported');
68
        }
69
70
        $this->outputFormat = $outputFormat;
71
72
        return $this;
73
    }
74
75
    /**
76
     * Sets the layer method for \Imagicl::mergeImageLayers()
77
     * If int, should correspond to a predefined LAYERMETHOD constant.
78
     * If null, \Imagicl::mergeImageLayers() will not be called.
79
     *
80
     * @param int|null
81
     *
82
     * @return $this
83
     *
84
     * @throws \Spatie\PdfToImage\Exceptions\InvalidLayerMethod
85
     *
86
     * @see https://secure.php.net/manual/en/imagick.constants.php
87
     * @see Pdf::getImageData()
88
     */
89
    public function setLayerMethod($layerMethod)
90
    {
91
        if (
92
            is_int($layerMethod) === false &&
93
            is_null($layerMethod) === false
94
        ) {
95
            throw new InvalidLayerMethod('LayerMethod must be integer or null');
96
        }
97
98
        $this->layerMethod = $layerMethod;
99
    }
100
101
    /**
102
     * Determine if the given format is a valid output format.
103
     *
104
     * @param $outputFormat
105
     *
106
     * @return bool
107
     */
108
    public function isValidOutputFormat($outputFormat)
109
    {
110
        return in_array($outputFormat, $this->validOutputFormats);
111
    }
112
113
    /**
114
     * Set the page number that should be rendered.
115
     *
116
     * @param int $page
117
     *
118
     * @return $this
119
     *
120
     * @throws \Spatie\PdfToImage\Exceptions\PageDoesNotExist
121
     */
122
    public function setPage($page)
123
    {
124
        if ($page > $this->getNumberOfPages()) {
125
            throw new PageDoesNotExist('Page '.$page.' does not exist');
126
        }
127
128
        $this->page = $page;
129
130
        return $this;
131
    }
132
133
    /**
134
     * Get the number of pages in the pdf file.
135
     *
136
     * @return int
137
     */
138
    public function getNumberOfPages()
139
    {
140
        return $this->imagick->getNumberImages();
141
    }
142
143
    /**
144
     * Save the image to the given path.
145
     *
146
     * @param string $pathToImage
147
     *
148
     * @return bool
149
     */
150
    public function saveImage($pathToImage)
151
    {
152
        $imageData = $this->getImageData($pathToImage);
153
154
        return file_put_contents($pathToImage, $imageData) === false ? false : true;
155
    }
156
157
    /**
158
     * Save the file as images to the given directory.
159
     *
160
     * @param string $directory
161
     * @param string $prefix
162
     *
163
     * @return array $files the paths to the created images
164
     */
165
    public function saveAllPagesAsImages($directory, $prefix = '')
166
    {
167
        $numberOfPages = $this->getNumberOfPages();
168
169
        if ($numberOfPages === 0) {
170
            return [];
171
        }
172
173
        return array_map(function ($pageNumber) use ($directory, $prefix) {
174
            $this->setPage($pageNumber);
175
176
            $destination = "{$directory}/{$prefix}{$pageNumber}.{$this->outputFormat}";
177
178
            $this->saveImage($destination);
179
180
            return $destination;
181
        }, range(1, $numberOfPages));
182
    }
183
184
    /**
185
     * Return raw image data.
186
     *
187
     * @param string $pathToImage
188
     *
189
     * @return \Imagick
190
     */
191
    public function getImageData($pathToImage)
192
    {
193
        $this->imagick->setResolution($this->resolution, $this->resolution);
194
195
        $this->imagick->readImage(sprintf('%s[%s]', $this->pdfFile, $this->page - 1));
196
197
        if (is_int($this->layerMethod)) {
198
            $this->imagick->mergeImageLayers($this->layerMethod);
199
        }
200
201
        $this->imagick->setFormat($this->determineOutputFormat($pathToImage));
202
203
        return $this->imagick;
204
    }
205
206
    /**
207
     * Determine in which format the image must be rendered.
208
     *
209
     * @param $pathToImage
210
     *
211
     * @return string
212
     */
213
    protected function determineOutputFormat($pathToImage)
214
    {
215
        $outputFormat = pathinfo($pathToImage, PATHINFO_EXTENSION);
216
217
        if ($this->outputFormat != '') {
218
            $outputFormat = $this->outputFormat;
219
        }
220
221
        $outputFormat = strtolower($outputFormat);
222
223
        if (! $this->isValidOutputFormat($outputFormat)) {
224
            $outputFormat = 'jpg';
225
        }
226
227
        return $outputFormat;
228
    }
229
}
230