Completed
Pull Request — master (#106)
by Matheus
01:17
created

Pdf::setFileName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Spatie\PdfToImage;
4
5
use Imagick;
6
use Spatie\PdfToImage\Exceptions\InvalidFormat;
7
use Spatie\PdfToImage\Exceptions\PdfDoesNotExist;
8
use Spatie\PdfToImage\Exceptions\PageDoesNotExist;
9
use Spatie\PdfToImage\Exceptions\InvalidLayerMethod;
10
11
class Pdf
12
{
13
    protected $pdfFile;
14
15
    protected $resolution = 144;
16
17
    protected $outputFormat = 'jpg';
18
19
    protected $page = 1;
20
21
    public $imagick;
22
23
    protected $numberOfPages;
24
25
    protected $validOutputFormats = ['jpg', 'jpeg', 'png'];
26
27
    protected $layerMethod = Imagick::LAYERMETHOD_FLATTEN;
28
29
    protected $colorspace;
30
31
    protected $compressionQuality;
32
33
    protected $fileName;
34
35
    /**
36
     * @param string $pdfFile The path or url to the pdffile.
37
     *
38
     * @throws \Spatie\PdfToImage\Exceptions\PdfDoesNotExist
39
     */
40
    public function __construct($pdfFile)
41
    {
42
        if (! filter_var($pdfFile, FILTER_VALIDATE_URL) && ! file_exists($pdfFile)) {
43
            throw new PdfDoesNotExist();
44
        }
45
46
        $this->imagick = new Imagick($pdfFile);
47
48
        $this->numberOfPages = $this->imagick->getNumberImages();
49
50
        $this->pdfFile = $pdfFile;
51
    }
52
53
    /**
54
     * Set the raster resolution.
55
     *
56
     * @param int $resolution
57
     *
58
     * @return $this
59
     */
60
    public function setResolution($resolution)
61
    {
62
        $this->resolution = $resolution;
63
64
        return $this;
65
    }
66
67
    /**
68
     * Set the output format.
69
     *
70
     * @param string $outputFormat
71
     *
72
     * @return $this
73
     *
74
     * @throws \Spatie\PdfToImage\Exceptions\InvalidFormat
75
     */
76
    public function setOutputFormat($outputFormat)
77
    {
78
        if (! $this->isValidOutputFormat($outputFormat)) {
79
            throw new InvalidFormat("Format {$outputFormat} is not supported");
80
        }
81
82
        $this->outputFormat = $outputFormat;
83
84
        return $this;
85
    }
86
87
    /**
88
     * Get the output format.
89
     *
90
     * @return string
91
     */
92
    public function getOutputFormat()
93
    {
94
        return $this->outputFormat;
95
    }
96
97
    /**
98
     * Sets the layer method for Imagick::mergeImageLayers()
99
     * If int, should correspond to a predefined LAYERMETHOD constant.
100
     * If null, Imagick::mergeImageLayers() will not be called.
101
     *
102
     * @param int|null
103
     *
104
     * @return $this
105
     *
106
     * @throws \Spatie\PdfToImage\Exceptions\InvalidLayerMethod
107
     *
108
     * @see https://secure.php.net/manual/en/imagick.constants.php
109
     * @see Pdf::getImageData()
110
     */
111
    public function setLayerMethod($layerMethod)
112
    {
113
        if (
114
            is_int($layerMethod) === false &&
115
            is_null($layerMethod) === false
116
        ) {
117
            throw new InvalidLayerMethod('LayerMethod must be an integer or null');
118
        }
119
120
        $this->layerMethod = $layerMethod;
121
122
        return $this;
123
    }
124
125
    /**
126
     * Determine if the given format is a valid output format.
127
     *
128
     * @param $outputFormat
129
     *
130
     * @return bool
131
     */
132
    public function isValidOutputFormat($outputFormat)
133
    {
134
        return in_array($outputFormat, $this->validOutputFormats);
135
    }
136
137
    /**
138
     * Set the page number that should be rendered.
139
     *
140
     * @param int $page
141
     *
142
     * @return $this
143
     *
144
     * @throws \Spatie\PdfToImage\Exceptions\PageDoesNotExist
145
     */
146
    public function setPage($page)
147
    {
148
        if ($page > $this->getNumberOfPages() || $page < 1) {
149
            throw new PageDoesNotExist("Page {$page} does not exist");
150
        }
151
152
        $this->page = $page;
153
154
        return $this;
155
    }
156
157
    /**
158
     * Get the number of pages in the pdf file.
159
     *
160
     * @return int
161
     */
162
    public function getNumberOfPages()
163
    {
164
        return $this->numberOfPages;
165
    }
166
167
168
    /**
169
     * Defines a custom name to save the file
170
     *
171
     * @return $this
172
     */
173
    public function setFileName($fileName)
174
    {
175
        $this->fileName = $fileName;
176
177
        return $this;
178
    }
179
180
    /**
181
     * Returns the current file name that is going to be used to save the file
182
     *
183
     * @return string|null
184
     */
185
    public function getFileName()
186
    {
187
        return $this->fileName;
188
    }
189
190
    /**
191
     * Save the image to the given path.
192
     *
193
     * @param string $pathToImage
194
     *
195
     * @return bool
196
     */
197
    public function saveImage($pathToImage)
198
    {
199
        if (is_dir($pathToImage)) {
200
            $fileName = $this->fileName ? $this->fileName : $this->page;
201
202
            $pathToImage = rtrim($pathToImage, '\/').DIRECTORY_SEPARATOR.$fileName.'.'.$this->outputFormat;
203
        }
204
205
        $imageData = $this->getImageData($pathToImage);
206
207
        return file_put_contents($pathToImage, $imageData) !== false;
208
    }
209
210
    /**
211
     * Save the file as images to the given directory.
212
     *
213
     * @param string $directory
214
     * @param string $prefix
215
     *
216
     * @return array $files the paths to the created images
217
     */
218
    public function saveAllPagesAsImages($directory, $prefix = '')
219
    {
220
        $numberOfPages = $this->getNumberOfPages();
221
222
        if ($numberOfPages === 0) {
223
            return [];
224
        }
225
226
        return array_map(function ($pageNumber) use ($directory, $prefix) {
227
            $this->setPage($pageNumber);
228
229
            $destination = "{$directory}/{$prefix}{$pageNumber}.{$this->outputFormat}";
230
231
            $this->saveImage($destination);
232
233
            return $destination;
234
        }, range(1, $numberOfPages));
235
    }
236
237
    /**
238
     * Return raw image data.
239
     *
240
     * @param string $pathToImage
241
     *
242
     * @return \Imagick
243
     */
244
    public function getImageData($pathToImage)
245
    {
246
        /*
247
         * Reinitialize imagick because the target resolution must be set
248
         * before reading the actual image.
249
         */
250
        $this->imagick = new Imagick();
251
252
        $this->imagick->setResolution($this->resolution, $this->resolution);
253
254
        if ($this->colorspace !== null) {
255
            $this->imagick->setColorspace($this->colorspace);
256
        }
257
258
        if ($this->compressionQuality !== null) {
259
            $this->imagick->setCompressionQuality($this->compressionQuality);
260
        }
261
262
        if (filter_var($this->pdfFile, FILTER_VALIDATE_URL)) {
263
            return $this->getRemoteImageData($pathToImage);
264
        }
265
266
        $this->imagick->readImage(sprintf('%s[%s]', $this->pdfFile, $this->page - 1));
267
268
        if (is_int($this->layerMethod)) {
269
            $this->imagick = $this->imagick->mergeImageLayers($this->layerMethod);
270
        }
271
272
        $this->imagick->setFormat($this->determineOutputFormat($pathToImage));
273
274
        return $this->imagick;
275
    }
276
277
    /**
278
     * @param int $colorspace
279
     *
280
     * @return $this
281
     */
282
    public function setColorspace(int $colorspace)
283
    {
284
        $this->colorspace = $colorspace;
285
286
        return $this;
287
    }
288
289
    /**
290
     * @param int $compressionQuality
291
     *
292
     * @return $this
293
     */
294
    public function setCompressionQuality(int $compressionQuality)
295
    {
296
        $this->compressionQuality = $compressionQuality;
297
298
        return $this;
299
    }
300
301
    /**
302
     * Return remote raw image data.
303
     *
304
     * @param string $pathToImage
305
     *
306
     * @return \Imagick
307
     */
308
    protected function getRemoteImageData($pathToImage)
309
    {
310
        $this->imagick->readImage($this->pdfFile);
311
312
        $this->imagick->setIteratorIndex($this->page - 1);
313
314
        if (is_int($this->layerMethod)) {
315
            $this->imagick = $this->imagick->mergeImageLayers($this->layerMethod);
316
        }
317
318
        $this->imagick->setFormat($this->determineOutputFormat($pathToImage));
319
320
        return $this->imagick;
321
    }
322
323
    /**
324
     * Determine in which format the image must be rendered.
325
     *
326
     * @param $pathToImage
327
     *
328
     * @return string
329
     */
330
    protected function determineOutputFormat($pathToImage)
331
    {
332
        $outputFormat = pathinfo($pathToImage, PATHINFO_EXTENSION);
333
334
        if ($this->outputFormat != '') {
335
            $outputFormat = $this->outputFormat;
336
        }
337
338
        $outputFormat = strtolower($outputFormat);
339
340
        if (! $this->isValidOutputFormat($outputFormat)) {
341
            $outputFormat = 'jpg';
342
        }
343
344
        return $outputFormat;
345
    }
346
}
347