spatie/pdf-to-image

repository·main·Indexed 23 days ago

https://github.com/spatie/pdf-to-image

A PHP package providing a simple interface for converting PDF documents into images using Imagick and Ghostscript. It supports selecting specific pages, configuring output formats (JPG, PNG, WebP), adjusting resolution and quality, resizing images, and managing background colors. The package requires PHP 8.2 or higher, with version 2.0 available for older PHP versions.

Tokens
1.9K
Snippets
7
Records
16
Agent score
78%

What's inside spatie/pdf-to-image

  1. Convert a PDF to an image

    main

    To convert a PDF to an image, instantiate the Spatie\PdfToImage\Pdf class with the path to your PDF, then call the save() method with the desired output path.

    Note on formats:

    • If the filename passed to save() has extensions like jpg, jpeg, png, or webp, the image will be saved in that format.
    • If no extension is provided, the output format defaults to jpg.

    Return values:

    • If saving a single page: returns a string containing the path to the saved image.
    • If saving multiple pages: returns an array of filenames.
    $pdf = new \Spatie\PdfToImage\Pdf($pathToPdf);
    $pdf->save($pathToWhereImageShouldBeStored);
  2. Install spatie/pdf-to-image via Composer

    main

    Install the package using Composer. This package requires PHP 8.2 or higher. If you are using an older version of PHP (< 8.2), you must use version 2.0 of the package.

    composer require spatie/pdf-to-image
  3. Troubleshoot Ghostscript and Imagick issues

    main

    Ghostscript 'gs' command not found

    If you encounter Uncaught ImagickException: FailedToExecuteCommand 'gs', especially in a PHP-FPM environment, you need to ensure the gs binary is in the PATH. Add the following to your php-fpm.conf and restart PHP-FPM:

    env[PATH] = /usr/local/bin:/usr/bin:/bin

    Imagick Security Policy Error

    If you see attempt to perform an operation not allowed by the security policy 'PDF', you must update your ImageMagick policy.xml (usually in /etc/ImageMagick-[VERSION]/policy.xml) to allow PDF reading/writing:

    <policy domain="coder" rights="read | write" pattern="PDF" />

    Ultra-wide PDF issues

    For extremely wide PDFs, update your Imagick policy.xml to increase resource limits:

    <policy domain="resource" name="width" value="4GiB"/>
    <policy domain="resource" name="height" value="4GiB"/>
  4. Get PDF page count and dimensions

    main

    Use these methods to inspect the PDF properties:

    • pageCount(): Returns the total number of pages as an int.
    • getSize(): Returns a Spatie\PdfToImage\DTOs\PageSize object containing $width and $height properties.
    $numberOfPages = $pdf->pageCount();
    
    $size = $pdf->getSize();
    $width = $size->width;
    $height = $size->height;
  5. Configure output format, quality, and resolution

    main

    You can customize the output image properties using a fluent interface:

    • format(OutputFormat $format): Set the output format using the Spatie\PdfToImage\Enums\OutputFormat enum.
    • quality(int $quality): Set the compression quality from 0 to 100.
    • resolution(int $dpi): Set the output resolution in DPI.
    • backgroundColor(string $color): Set the background color using a color name (e.g., 'white'), hex code (e.g., '#fff'), or RGB string (e.g., 'rgb(255,255,255)').
    $pdf->format(\Spatie\PdfToImage\Enums\OutputFormat::Webp)
        ->quality(90)
        ->resolution(300)
        ->backgroundColor('white')
        ->save($pathToWhereImageShouldBeStored);
  6. Configure Imagick layer merging

    main

    You can control how Imagick handles layers using the layerMethod() method with the Spatie\PdfToImage\Enums\LayerMethod enum:

    • LayerMethod::Merge: Merges layers.
    • LayerMethod::None: Disables layer merging.
    $pdf->layerMethod(\Spatie\PdfToImage\Enums\LayerMethod::Merge);
  7. Resize output images

    main

    Control the dimensions of the output image using thumbnailSize() or size():

    • thumbnailSize(int $width, ?int $height = null): Sets the thumbnail width. If height is not provided, it is calculated automatically.
    • size(int $width, ?int $height = null): Sets the output image width. If height is not provided, it is calculated automatically.
  8. Select specific pages for conversion

    main

    By default, only the first page of a PDF is rendered. You can select specific pages using the following methods:

    • selectPage(int $page): Selects a single specific page.
    • selectPages(...int $pages): Selects multiple specific pages.

    When using selectPages(), the save() method must point to an existing directory rather than a specific file path.

    // Save the second page
    $pdf->selectPage(2)
        ->save($pathToWhereImageShouldBeStored);
    
    // Save the 2nd, 4th, and 5th pages to a directory
    $pdf->selectPages(2, 4, 5)
        ->save($directoryToWhereImageShouldBeStored);
  9. Resize and create thumbnails

    main

    You can resize the output images using these methods:

    • size(int $width, ?int $height = null): Resizes the image to the specified width. If $height is not provided, it scales proportionally.
    • thumbnailSize(int $width, ?int $height = null): Creates a thumbnail of the specified size. If $height is not provided, it scales proportionally.

    Both methods throw InvalidSize if negative dimensions are provided.

  10. Configure image resolution and quality

    main

    You can control the output quality and sharpness using the following methods:

    • resolution(int $dpiResolution): Sets the DPI (dots per inch). The default is 144.
    • quality(int $compressionQuality): Sets the compression quality from 1 (lowest) to 100 (highest). Throws InvalidQuality if out of range.
    • antialiased(bool $antiAliased): Enables or disables antialiasing. Defaults to true.