diff --git a/README.md b/README.md index 6e80138..6c39ee5 100644 --- a/README.md +++ b/README.md @@ -138,6 +138,19 @@ $pdf->layerMethod(\Spatie\PdfToImage\Enums\LayerMethod::Merge); $pdf->layerMethod(\Spatie\PdfToImage\Enums\LayerMethod::None); ``` +Set the background color of the output image: + +```php +$pdf->backgroundColor('white') // simple text for 'white' color + ->save($pathToWhereImageShouldBeStored); + +$pdf->backgroundColor('#fff') // code for 'white' color + ->save($pathToWhereImageShouldBeStored); + +$pdf->backgroundColor('rgb(255,255,255)') // rgb for 'white' color + ->save($pathToWhereImageShouldBeStored); +``` + ## Issues regarding Ghostscript This package uses Ghostscript through Imagick. For this to work Ghostscripts `gs` command should be accessible from the PHP process. For the PHP CLI process (e.g. Laravel's asynchronous jobs, commands, etc...) this is usually already the case. diff --git a/src/Pdf.php b/src/Pdf.php index a3ba2f2..5b3920d 100644 --- a/src/Pdf.php +++ b/src/Pdf.php @@ -12,6 +12,7 @@ use Spatie\PdfToImage\Exceptions\InvalidSize; use Spatie\PdfToImage\Exceptions\PageDoesNotExist; use Spatie\PdfToImage\Exceptions\PdfDoesNotExist; +use ImagickPixel; class Pdf { @@ -19,6 +20,8 @@ class Pdf protected int $resolution = 144; + protected ?string $backgroundColor = null; + protected OutputFormat $outputFormat = OutputFormat::Jpg; protected array $pages = [1]; @@ -61,6 +64,16 @@ public function resolution(int $dpiResolution): static return $this; } + /** + * Set the background color e.g. 'white', '#fff', 'rgb(255, 255, 255)' + */ + public function backgroundColor(string $backgroundColorCode): static + { + $this->backgroundColor = $backgroundColorCode; + + return $this; + } + /** * Sets the output format of the generated image. * Default is OutputFormat::Jpg. @@ -234,6 +247,11 @@ public function getImageData(string $pathToImage, int $pageNumber): Imagick $this->imagick->readImage(sprintf('%s[%s]', $this->filename, $pageNumber - 1)); + if (! empty($this->backgroundColor)) { + $this->imagick->setImageBackgroundColor(new ImagickPixel($this->backgroundColor)); + $this->imagick->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE); + } + if ($this->resizeWidth !== null) { $this->imagick->resizeImage($this->resizeWidth, $this->resizeHeight ?? 0, Imagick::FILTER_POINT, 0); } diff --git a/tests/Unit/PdfTest.php b/tests/Unit/PdfTest.php index 2459be2..05df5c9 100644 --- a/tests/Unit/PdfTest.php +++ b/tests/Unit/PdfTest.php @@ -48,3 +48,15 @@ expect($imagick1)->toBeInstanceOf(Imagick::class); }); + +it('can set the background color', function ($backgroundColor) { + $image = (new Pdf($this->testFile)) + ->backgroundColor($backgroundColor) + ->selectPage(1) + ->getImageData('page-1.jpg', 1) + ->getImageBackgroundColor() + ->getColorAsString(); + + $expectedSRGBValueForWhiteColor = 'srgb(255,255,255)'; + expect($image)->toEqual($expectedSRGBValueForWhiteColor); +})->with(['srgb(255,255,255)', 'rgb(255,255,255)', 'white', '#fff']);