PHPackages                             baraja-core/php-pdf-to-image - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [PDF &amp; Document Generation](/categories/documents)
4. /
5. baraja-core/php-pdf-to-image

ActiveLibrary[PDF &amp; Document Generation](/categories/documents)

baraja-core/php-pdf-to-image
============================

Convert PDF to JPG, PNG or GIF in PHP.

v2.0.1(1y ago)2315.8k↓30.6%9[1 issues](https://github.com/baraja-core/php-pdf-to-image/issues)PHPPHP ^8.0CI failing

Since Nov 12Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/baraja-core/php-pdf-to-image)[ Packagist](https://packagist.org/packages/baraja-core/php-pdf-to-image)[ Docs](https://github.com/baraja-core/php-pdf-to-image)[ RSS](/packages/baraja-core-php-pdf-to-image/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (9)Dependencies (7)Versions (13)Used By (0)

PHP PDF to Image
================

[](#php-pdf-to-image)

A lightweight PHP library for converting PDF documents to image files. Supports JPG, PNG, and GIF output formats with optional image scaling and whitespace trimming.

Key Principles
--------------

[](#key-principles)

- **Simple static API** - Single method call to convert PDF to image
- **Multiple formats** - Supports JPG, PNG, and GIF output formats
- **Image manipulation** - Optional scaling and whitespace trimming built-in
- **Zero dependencies** - Only requires PHP 8.0+ and the Imagick extension
- **Auto-directory creation** - Automatically creates output directories if they don't exist
- **Strict typing** - Fully typed with PHP 8 strict mode enabled

Architecture
------------

[](#architecture)

The library follows a clean, minimal architecture with three main components:

```
┌─────────────────────────────────────────────────────────────┐
│                      User Application                       │
└─────────────────────────────┬───────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                     Configuration                            │
│  ┌─────────────────────────────────────────────────────┐    │
│  │ • pdfPath      - Source PDF file path               │    │
│  │ • savePath     - Output image file path             │    │
│  │ • format       - Output format (jpg/png/gif)        │    │
│  │ • trim         - Remove whitespace borders          │    │
│  │ • cols/rows    - Scale dimensions                   │    │
│  │ • bestfit      - Maintain aspect ratio on scale     │    │
│  └─────────────────────────────────────────────────────┘    │
└─────────────────────────────┬───────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                       Convertor                              │
│  ┌─────────────────────────────────────────────────────┐    │
│  │ convert(Configuration): void                        │    │
│  │   ├── Validates Imagick availability                │    │
│  │   ├── Loads PDF via Imagick                         │    │
│  │   ├── Applies format conversion                     │    │
│  │   ├── Applies optional scaling                      │    │
│  │   ├── Applies optional trimming                     │    │
│  │   └── Writes output file to disk                    │    │
│  └─────────────────────────────────────────────────────┘    │
└─────────────────────────────┬───────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                   ConvertorException                         │
│  Custom exception for all conversion-related errors          │
└─────────────────────────────────────────────────────────────┘

```

### Components

[](#components)

ComponentDescription`Configuration`Immutable value object that holds all conversion parameters. Validates input on construction and provides format constants.`Convertor`Static utility class that performs the actual PDF-to-image conversion using Imagick. Cannot be instantiated.`ConvertorException`Custom exception thrown when conversion fails (file not found, write errors, Imagick errors).📦 Installation
--------------

[](#-installation)

It's best to use [Composer](https://getcomposer.org) for installation, and you can also find the package on [Packagist](https://packagist.org/packages/baraja-core/php-pdf-to-image) and [GitHub](https://github.com/baraja-core/php-pdf-to-image).

To install, simply use the command:

```
$ composer require baraja-core/php-pdf-to-image
```

### Requirements

[](#requirements)

- **PHP 8.0** or higher
- **Imagick extension** (`ext-imagick`)

#### Installing Imagick

[](#installing-imagick)

On Debian/Ubuntu:

```
$ sudo apt-get install php-imagick
```

On macOS with Homebrew:

```
$ brew install imagemagick
$ pecl install imagick
```

Make sure Ghostscript is also installed for PDF processing:

```
# Debian/Ubuntu
$ sudo apt-get install ghostscript

# macOS
$ brew install ghostscript
```

Basic Usage
-----------

[](#basic-usage)

### Simple Conversion

[](#simple-conversion)

The most straightforward way to convert a PDF to an image:

```
use Baraja\PdfToImage\Configuration;
use Baraja\PdfToImage\Convertor;

$configuration = new Configuration(
    pdfPath: '/path/to/document.pdf',
    savePath: '/path/to/output.jpg',
    format: 'jpg'
);

Convertor::convert($configuration);
```

### Using the Factory Method

[](#using-the-factory-method)

You can also use the static factory method for configuration:

```
use Baraja\PdfToImage\Configuration;
use Baraja\PdfToImage\Convertor;

$configuration = Configuration::from(
    pdfPath: '/path/to/document.pdf',
    savePath: '/path/to/output.png',
    format: 'png',
    trim: true
);

Convertor::convert($configuration);
```

### Converting with Image Scaling

[](#converting-with-image-scaling)

To resize the output image during conversion:

```
use Baraja\PdfToImage\Configuration;
use Baraja\PdfToImage\Convertor;

$configuration = new Configuration(
    pdfPath: '/path/to/document.pdf',
    savePath: '/path/to/thumbnail.jpg',
    format: 'jpg',
    cols: 800,    // Width in pixels
    rows: 600,    // Height in pixels
    bestfit: true // Maintain aspect ratio
);

Convertor::convert($configuration);
```

### Trimming Whitespace

[](#trimming-whitespace)

To automatically remove white borders from the resulting image:

```
use Baraja\PdfToImage\Configuration;
use Baraja\PdfToImage\Convertor;

$configuration = new Configuration(
    pdfPath: '/path/to/document.pdf',
    savePath: '/path/to/trimmed.png',
    format: 'png',
    trim: true
);

Convertor::convert($configuration);
```

### Full Example with Error Handling

[](#full-example-with-error-handling)

```
use Baraja\PdfToImage\Configuration;
use Baraja\PdfToImage\Convertor;
use Baraja\PdfToImage\ConvertorException;

try {
    $configuration = new Configuration(
        pdfPath: __DIR__ . '/documents/report.pdf',
        savePath: __DIR__ . '/images/report-preview.jpg',
        format: 'jpg',
        trim: true,
        cols: 1200,
        rows: 900,
        bestfit: true
    );

    Convertor::convert($configuration);

    echo 'PDF converted successfully!';
} catch (ConvertorException $e) {
    echo 'Conversion failed: ' . $e->getMessage();
}
```

Configuration Options
---------------------

[](#configuration-options)

OptionTypeDefaultDescription`pdfPath``string`*required*Absolute or relative path to the source PDF file. The file must exist.`savePath``string`*required*Path where the output image will be saved. Parent directories are created automatically.`format``string``'jpg'`Output image format. Must be one of: `jpg`, `png`, `gif`.`trim``bool``false`When `true`, removes white borders from the resulting image.`cols``int|null``null`Target width in pixels for scaling. Must be set together with `rows`.`rows``int|null``null`Target height in pixels for scaling. Must be set together with `cols`.`bestfit``bool``false`When `true` and scaling is enabled, maintains aspect ratio (image may be smaller than specified dimensions).### Supported Output Formats

[](#supported-output-formats)

The library provides constants for supported formats:

```
use Baraja\PdfToImage\Configuration;

Configuration::FormatJpg;  // 'jpg'
Configuration::FormatPng;  // 'png'
Configuration::FormatGif;  // 'gif'

Configuration::SupportedFormats; // ['jpg', 'png', 'gif']
```

How It Works
------------

[](#how-it-works)

1. **Configuration Validation** - When you create a `Configuration` object, it validates:

    - The PDF file exists at the specified path
    - The output format is one of the supported formats (jpg, png, gif)
    - Format strings are normalized to lowercase
2. **Conversion Process** - When `Convertor::convert()` is called:

    - Verifies the Imagick extension is available
    - Loads the first page of the PDF using Imagick
    - Sets the output image format
    - Applies scaling if `cols` and `rows` are specified
    - Applies trimming if enabled (removes white borders with 1px tolerance)
    - Creates the output directory if it doesn't exist
    - Writes the image to disk with `0666` permissions
3. **Error Handling** - All errors are wrapped in `ConvertorException`:

    - File not found errors
    - Imagick processing errors
    - File write permission errors
    - Directory creation errors

Important Notes
---------------

[](#important-notes)

- **First Page Only** - The converter processes only the first page of multi-page PDF documents
- **Memory Usage** - Large PDF files or high-resolution outputs may require significant memory. Adjust PHP's `memory_limit` if needed
- **Ghostscript** - Imagick requires Ghostscript to be installed for PDF processing
- **Static Class** - The `Convertor` class is static and cannot be instantiated

Author
------

[](#author)

**Jan Barášek** -

📄 License
---------

[](#-license)

`baraja-core/php-pdf-to-image` is licensed under the MIT license. See the [LICENSE](https://github.com/baraja-core/php-pdf-to-image/blob/master/LICENSE) file for more details.

###  Health Score

48

—

FairBetter than 95% of packages

Maintenance58

Moderate activity, may be stable

Popularity37

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity69

Established project with proven stability

 Bus Factor1

Top contributor holds 97.3% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~230 days

Recently: every ~349 days

Total

9

Last Release

538d ago

Major Versions

v1.4.0 → v2.0.02022-10-24

PHP version history (4 changes)v1.0.0PHP &gt;=7.1.0

v1.2.0PHP &gt;=7.4.0

v1.3.0PHP ^7.4 || ^8.0

v1.4.0PHP ^8.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/3382204?v=4)[baraja](/maintainers/baraja)[@baraja](https://github.com/baraja)

---

Top Contributors

[![janbarasek](https://avatars.githubusercontent.com/u/4738758?v=4)](https://github.com/janbarasek "janbarasek (36 commits)")[![dependabot-preview[bot]](https://avatars.githubusercontent.com/in/2141?v=4)](https://github.com/dependabot-preview[bot] "dependabot-preview[bot] (1 commits)")

---

Tags

gifjpgpdfphp

###  Code Quality

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/baraja-core-php-pdf-to-image/health.svg)

```
[![Health](https://phpackages.com/badges/baraja-core-php-pdf-to-image/health.svg)](https://phpackages.com/packages/baraja-core-php-pdf-to-image)
```

###  Alternatives

[spatie/browsershot

Convert a webpage to an image or pdf using headless Chrome

5.2k32.1M102](/packages/spatie-browsershot)[barryvdh/laravel-snappy

Snappy PDF/Image for Laravel

2.8k24.8M48](/packages/barryvdh-laravel-snappy)[openspout/openspout

PHP Library to read and write spreadsheet files (CSV, XLSX and ODS), in a fast and scalable way

1.2k57.6M131](/packages/openspout-openspout)[keboola/csv

Keboola CSV reader and writer

1451.8M21](/packages/keboola-csv)[setasign/tfpdf

This class is a modified version of FPDF that adds UTF-8 support. The latest version is based on FPDF 1.85.

426.1M30](/packages/setasign-tfpdf)[aspera/xlsx-reader

Spreadsheet reader library for XLSX files

52742.2k5](/packages/aspera-xlsx-reader)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
