From ad9b2ebb138eed4ced3890f865abc5ad33f3bb40 Mon Sep 17 00:00:00 2001 From: Bashir ABDEL WAHED Date: Thu, 12 Nov 2026 19:56:46 +0100 Subject: [PATCH 1/8] Sync SDK image APIs and compression errors Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/Image/ImageCompressor.php | 4 +- src/Image/ImageExtractor.php | 24 +- src/Input/LocalInputSource.php | 6 +- stubs/bernard_ledit.stubs.php | 425 +++++++++++++-------------- tests/Input/LocalInputSourceTest.php | 4 +- 5 files changed, 238 insertions(+), 225 deletions(-) diff --git a/src/Image/ImageCompressor.php b/src/Image/ImageCompressor.php index 5163e7a5..3679b779 100644 --- a/src/Image/ImageCompressor.php +++ b/src/Image/ImageCompressor.php @@ -10,7 +10,7 @@ use Mindee\Error\MindeeImageException; use Mindee\Error\MindeeUnhandledException; -use function BernardLedit\Image\compress as compressImage; +use function BernardLedit\Image\compressToJpeg as compressImage; /** * Image compressor class to handle image compression. @@ -36,7 +36,7 @@ public static function compress( ): string { DependencyChecker::requireBernardLedit(); try { - [$bytes] = compressImage($inputImage, $quality, $maxWidth, $maxHeight); + [$bytes] = compressImage($inputImage, $quality, null, $maxWidth, $maxHeight); return $bytes; } catch (Exception $e) { throw new MindeeImageException("Image compression failed.", ErrorCode::FILE_OPERATION_ABORTED, $e); diff --git a/src/Image/ImageExtractor.php b/src/Image/ImageExtractor.php index ff9736e0..69418158 100644 --- a/src/Image/ImageExtractor.php +++ b/src/Image/ImageExtractor.php @@ -6,8 +6,7 @@ use BernardLedit\Image\Image; use BernardLedit\Image\ImageException; -use BernardLedit\Image\ImageExtractException; -use BernardLedit\Pdf\PdfExtractException; +use BernardLedit\Pdf\PdfDocument; use BernardLedit\Pdf\PdfiumException; use InvalidArgumentException; use Mindee\Dependency\DependencyChecker; @@ -17,10 +16,10 @@ use Mindee\Geometry\Point; use Mindee\Geometry\Polygon; use Mindee\Input\LocalInputSource; +use Mindee\Pdf\PdfUtils; use ValueError; use function BernardLedit\Image\guessFormat; -use function BernardLedit\Image\extractFromPolygons; use function count; use function sprintf; use function is_array; @@ -204,8 +203,23 @@ protected function cropPolygons(array $polygons, int $pageIndex): array { $pairs = array_map(static::polygonToPairs(...), $polygons); try { - return extractFromPolygons($this->sourceData, $pageIndex, $pairs, $this->pdfDpi); - } catch (ImageException|ImageExtractException|PdfExtractException|PdfiumException|ValueError $e) { + if ($this->inputSource->isPdf()) { + $pdf = new PdfDocument($this->sourceData); + try { + $bitmap = $pdf->getPage($pageIndex)->renderToBitmap($this->pdfDpi / 72.0); + $sourceImage = new Image($bitmap->toPngBytes()); + } finally { + PdfUtils::closeQuietly($pdf); + } + } else { + $sourceImage = new Image($this->sourceData); + } + + return array_map( + static fn(array $polygon): Image => $sourceImage->cropPolygon($polygon), + $pairs + ); + } catch (ImageException|PdfiumException|ValueError $e) { throw new MindeeImageException($e->getMessage(), $e->getCode(), $e); } } diff --git a/src/Input/LocalInputSource.php b/src/Input/LocalInputSource.php index 8dae43dd..a230a63d 100644 --- a/src/Input/LocalInputSource.php +++ b/src/Input/LocalInputSource.php @@ -25,8 +25,8 @@ use function BernardLedit\Pdf\applyPageOptions as nativeApplyPageOptions; use function BernardLedit\Pdf\fixPdf as nativeFixPdf; use function in_array; -use function BernardLedit\Image\compress as compressImage; -use function BernardLedit\Pdf\compress as compressPdf; +use function BernardLedit\Image\compressToJpeg as compressImage; +use function BernardLedit\Pdf\compressToJpeg as compressPdf; /** * List of allowed mime types for document parsing. @@ -284,7 +284,7 @@ public function compress( if ($this->isPdf()) { $compressed = compressPdf($bytes, $quality, $optimize, $dpi); } else { - [$compressed] = compressImage($bytes, $quality, $maxWidth, $maxHeight, $optimize); + [$compressed] = compressImage($bytes, $quality, $optimize, $maxWidth, $maxHeight); if ($compressed !== $bytes) { $this->fileMimetype = 'image/jpeg'; $extension = strtolower(pathinfo($this->fileName, PATHINFO_EXTENSION)); diff --git a/stubs/bernard_ledit.stubs.php b/stubs/bernard_ledit.stubs.php index 6f1c2e8e..8554bd92 100644 --- a/stubs/bernard_ledit.stubs.php +++ b/stubs/bernard_ledit.stubs.php @@ -1,5 +1,5 @@ $left + * @param int<0, 4294967295> $top + * @param int<0, 4294967295> $right + * @param int<0, 4294967295> $bottom * @return \BernardLedit\Image\Image - * @throws \Exception Returns an error if the cropping operation fails. + * @throws \ValueError if a coordinate is out of range, or the box is empty or extends past the image. */ public function crop(int $left, int $top, int $right, int $bottom): \BernardLedit\Image\Image {} + /** + * Crops the bounding box of a polygon from this image. + * + * @param list $polygon Normalized points relative to the image size. + * @return \BernardLedit\Image\Image + * @throws \ValueError if the polygon is empty, malformed, or its bounding box is empty. + * @throws \BernardLedit\Image\ImageException if cropping fails. + */ + public function cropPolygon(array $polygon): \BernardLedit\Image\Image {} + /** * Returns the encoded bytes as a PHP string. * - * @param string $format - * @param int $quality - * @param bool $optimize + * @param string $format An output format: `"JPEG"`, `"PNG"`, `"PDF"`, etc. + * @param int<1, 100> $jpeg_quality Only used by JPEG and PDF. + * @param bool $jpeg_optimize Optimize JPEG Huffman tables. * @return string - * @throws \Exception Returns an error if the encoding operation fails. + * @throws \ValueError if `$format` isn't a supported output format, or `$jpeg_quality` is out of range. + * @throws \BernardLedit\Image\ImageException if encoding fails. */ - public function encode(string $format, int $quality = 85, bool $optimize = true): string {} + public function encode(string $format, int $jpeg_quality = 85, bool $jpeg_optimize = true): string {} /** * Upper-case format name (`"JPEG"`, `"PNG"`, etc.) or `null`. * * @return string|null - * @throws \Exception Returns an error if the format name cannot be converted to a string. */ public function getFormat(): ?string {} @@ -53,9 +63,9 @@ public function getFormat(): ?string {} public function getHeight(): int {} /** - * Dimensions as `[width, height]`. + * Dimensions in pixels. * - * @return array + * @return array{0: int, 1: int} `[$width, $height]`. */ public function getSize(): array {} @@ -67,110 +77,125 @@ public function getSize(): array {} public function getWidth(): int {} /** - * Resizes an image using dimensions and a filter. + * Resizes the image to `$width` by `$height` pixels, with a Lanczos filter. * - * @param int $width - * @param int $height + * @param int<1, 4294967295> $width + * @param int<1, 4294967295> $height * @return \BernardLedit\Image\Image - * @throws \Exception Returns an error if the resizing operation fails. + * @throws \ValueError if `$width` or `$height` is out of range. */ public function resize(int $width, int $height): \BernardLedit\Image\Image {} } /** - * `BernardLedit\Image\ImageException extends \Exception` Decode and encode failures. - */ - class ImageException extends \Exception { - public function __construct() {} - } - - /** - * `BernardLedit\Image\ImageExtractException extends \Exception` Decode and encode failures. - */ - class ImageExtractException extends \Exception { - public function __construct() {} - } - - /** - * Compresses an image. + * Compresses an image as a JPEG, scaled down to fit `$max_width` and `$max_height`. * * @param string $data - * @param int $quality - * @param int|null $max_width - * @param int|null $max_height + * @param int<5, 100> $quality + * @param int<1, 4294967295>|null $max_width + * @param int<1, 4294967295>|null $max_height * @param bool|null $optimize - * @return array - * @throws \Exception Returns an error if the compression operation fails, or if the resulting dimensions - * @throws \Exception don't fit in a 32-bit integer. + * @return array{0: string, 1: int, 2: int} `[$bytes, $width, $height]`. + * @throws \ValueError if `$quality`, `$max_width` or `$max_height` is out of range. + * @throws \BernardLedit\Image\ImageException if `$data` isn't an identifiable image, can't be decoded or encoded, or the output isn't smaller. */ - function compress(string $data, int $quality = 85, ?int $max_width = null, ?int $max_height = null, ?bool $optimize = null): array {} + function compressToJpeg(string $data, int $quality = 85, ?bool $optimize = null, ?int $max_width = null, ?int $max_height = null): array {} /** * `BernardLedit\Image\decode(string $data): Image` * * @param string $data * @return \BernardLedit\Image\Image - * @throws \Exception Returns an error if the decoding operation fails. + * @throws \BernardLedit\Image\ImageException if `$data` isn't an identifiable image, or can't be decoded. */ function decode(string $data): \BernardLedit\Image\Image {} - /** - * Extracts polygons from an image. - * - * @param string $data - * @param int $page_id - * @param array $polygons - * @param float $dpi - * @return array - * @throws \Exception Return an error if the image cannot be decoded or if the polygons cannot be extracted. - */ - function extractFromPolygons(string $data, int $page_id, array $polygons, float $dpi = 72.0): array {} - /** * `BernardLedit\Image\guessFormat(string $data): string` * * @param string $data * @return string - * @throws \Exception Returns an error if the decoding operation fails. + * @throws \BernardLedit\Image\ImageException if `$data` isn't an identifiable image. */ function guessFormat(string $data): string {} } namespace BernardLedit\Pdf { - class PdfDocument { + class PdfBitmap { + public function __construct() {} + /** - * Create a new instance from bytes. + * Debug info. * - * @param string $data - * @throws \Exception Returns a PHP Exception if the creation fails. + * @return array */ - public function __construct(string $data) {} + public function __debugInfo(): array {} /** - * Append text to a page. + * String rep. * - * @param int $page_idx - * @param array $chars - * @return void - * @throws \Exception Returns a PHP Exception if the text append fails. + * @return string */ - public function addText(int $page_idx, array $chars): void {} + public function __toString(): string {} /** - * Appends a sequence of JPEG pages as pages to the document. + * Height in pixels. + * + * @return int + */ + public function getHeight(): int {} + + /** + * Width in pixels. + * + * @return int + */ + public function getWidth(): int {} + + /** + * Raw RGBA8 pixel buffer (row-major, 4 bytes per pixel). + * + * @return string + */ + public function toBytes(): string {} + + /** + * Encode the bitmap as a PNG byte stream. + * + * @return string + * @throws \BernardLedit\Image\ImageException if PNG encoding fails. + */ + public function toPngBytes(): string {} + } + + class PdfDocument { + /** + * Create a new instance from bytes. + * + * @param string $data + * @throws \BernardLedit\Pdf\PdfiumException if `PDFium` can't be loaded, or `$data` isn't a PDF it can read. + */ + public function __construct(string $data) {} + + /** + * Appends a JPEG as a page of the document. * * @param string $jpeg * @return void - * @throws \Exception Returns a PHP Exception if the append fails. + * @throws \BernardLedit\Image\ImageException if `$jpeg` is invalid, truncated or in an unsupported color space. + * @throws \BernardLedit\Pdf\PdfiumException if `PDFium` can't append the page. + * @throws \Exception if the document is closed. */ public function appendJpegPage(string $jpeg): void {} /** * Append multiple JPEG pages to the document. * - * @param array $jpegs + * @param list $jpegs * @return void - * @throws \Exception Returns a PHP Exception if the append fails. + * @throws \BernardLedit\Image\ImageException if one of `$jpegs` is invalid, truncated or in an unsupported color space. + * @throws \BernardLedit\Pdf\PdfiumException if `PDFium` can't append a page. + * @throws \Exception if the document is closed. */ public function appendMultipleJpegPages(array $jpegs): void {} @@ -178,15 +203,15 @@ public function appendMultipleJpegPages(array $jpegs): void {} * Returns the PDF bytes (PHP writes files itself and keeps I/O out of Rust). * * @return string - * @throws \Exception Returns a PHP Exception if the save fails. + * @throws \BernardLedit\Pdf\PdfiumException if `PDFium` can't save the document. + * @throws \Exception if the document is closed. */ public function asBytes(): string {} /** - * Close the document. + * Close the document. Closing it again does nothing. * * @return void - * @throws \Exception Returns a PHP Exception if the close fails. */ public function close(): void {} @@ -194,28 +219,33 @@ public function close(): void {} * Recompresses pages that have no text layer (scans) as JPEG. * Returns `null` when there is nothing to gain (e.g. text-only documents). * - * @param int $quality - * @param bool $optimize - * @param float $dpi + * @param int<5, 100> $quality + * @param bool $optimize Optimize JPEG Huffman tables. + * @param float $dpi A finite number between 1 and 1200. * @return \BernardLedit\Pdf\PdfDocument|null - * @throws \Exception Returns a PHP Exception if rendering or encoding fails. + * @throws \ValueError if `$quality` or `$dpi` is out of range. + * @throws \BernardLedit\Image\ImageException if JPEG encoding fails. + * @throws \BernardLedit\Pdf\PdfiumException if `PDFium` can't render a page, or build the new document. + * @throws \Exception if the document is closed. */ - public function compress(int $quality = 85, bool $optimize = true, float $dpi = 150.0): ?\BernardLedit\Pdf\PdfDocument {} + public function compressToJpeg(int $quality = 85, bool $optimize = true, float $dpi = 150.0): ?\BernardLedit\Pdf\PdfDocument {} /** * `PdfDocument::create()` empty document (new is reserved). * * @return \BernardLedit\Pdf\PdfDocument - * @throws \Exception Returns a PHP Exception if the creation fails. + * @throws \BernardLedit\Pdf\PdfiumException if `PDFium` can't be loaded, or can't create a document. */ public static function create(): \BernardLedit\Pdf\PdfDocument {} /** * Return the specified page. * - * @param int $index + * @param int<0, 65535> $index * @return \BernardLedit\Pdf\PdfPage - * @throws \Exception Returns a PHP Exception if the page cannot be retrieved. + * @throws \ValueError if `$index` is out of range, or there's no page `$index`. + * @throws \BernardLedit\Pdf\PdfiumException if `PDFium` can't load the page. + * @throws \Exception if the document is closed. */ public function getPage(int $index): \BernardLedit\Pdf\PdfPage {} @@ -223,7 +253,8 @@ public function getPage(int $index): \BernardLedit\Pdf\PdfPage {} * Returns the page count. * * @return int - * @throws \Exception Returns a PHP Exception if the count fails. + * @throws \ValueError if the document has more than 65535 pages. + * @throws \Exception if the document is closed. */ public function getPageCount(): int {} @@ -231,7 +262,8 @@ public function getPageCount(): int {} * Retrieves the entire text from a document as a string. * * @return string - * @throws \Exception Returns a PHP Exception if the text retrieval fails. + * @throws \BernardLedit\Pdf\PdfiumException if `PDFium` can't read a page's text. + * @throws \Exception if the document is closed. */ public function getText(): string {} @@ -239,7 +271,8 @@ public function getText(): string {} * Returns true if the document has no content. * * @return bool - * @throws \Exception Returns a PHP Exception if the check fails. + * @throws \BernardLedit\Pdf\PdfiumException if `PDFium` can't read a page. + * @throws \Exception if the document is closed. */ public function hasNoContent(): bool {} @@ -247,7 +280,8 @@ public function hasNoContent(): bool {} * Check if the document has any text. * * @return bool - * @throws \Exception Returns a PHP Exception if the check fails. + * @throws \BernardLedit\Pdf\PdfiumException if `PDFium` can't read a page. + * @throws \Exception if the document is closed. */ public function hasText(): bool {} @@ -255,25 +289,24 @@ public function hasText(): bool {} * Append pages `indexes` of `$src` to `$this`. * * @param \BernardLedit\Pdf\PdfDocument $src - * @param array $indexes + * @param list> $indexes * @return void - * @throws \Exception Returns a PHP Exception if the import fails. + * @throws \ValueError if an index is out of range, `$src` is this document, or `$src` has no page at one of `$indexes`. + * @throws \BernardLedit\Pdf\PdfiumException if `PDFium` can't copy the pages. + * @throws \Exception if either document is closed. */ public function importPages(\BernardLedit\Pdf\PdfDocument $src, array $indexes): void {} /** - * Rasterizes a page from a given index as a JPEG. + * Rasterizes a page from a given index into an image, at 72 DPI. * - * @param int $index - * @param int $quality - * @return string - * @throws \Exception Returns a PHP Exception if the rasterization fails. + * @param int<0, 65535> $index + * @return \BernardLedit\Image\Image + * @throws \ValueError if `$index` is out of range, or there's no page `$index`. + * @throws \BernardLedit\Pdf\PdfiumException if `PDFium` can't render the page. + * @throws \Exception if the document is closed. */ - public function rasterizePageToJpegBytes(int $index, int $quality): string {} - } - - class PdfExtractException extends \Exception { - public function __construct() {} + public function rasterizePage(int $index): \BernardLedit\Image\Image {} } class PdfPage { @@ -282,8 +315,9 @@ public function __construct() {} /** * Returns the characters on the page. * - * @return array - * @throws \Exception Returns a PHP Exception if the `PdfDocument` is inaccessible. + * @return list<\BernardLedit\Pdf\TextChar> + * @throws \BernardLedit\Pdf\PdfiumException if `PDFium` can't read the page's characters. + * @throws \Exception if the document is closed. */ public function getChars(): array {} @@ -295,10 +329,11 @@ public function getChars(): array {} public function getIndex(): int {} /** - * `[width, height]` in points. + * Dimensions in points. * - * @return array - * @throws \Exception Returns a PHP Exception if the `PdfDocument` is closed. + * @return array{0: float, 1: float} `[$width, $height]`. + * @throws \BernardLedit\Pdf\PdfiumException if `PDFium` can't load the page. + * @throws \Exception if the document is closed. */ public function getSize(): array {} @@ -306,41 +341,75 @@ public function getSize(): array {} * Returns the text of the page. * * @return string - * @throws \Exception Returns a PHP Exception if the `PdfDocument` is inaccessible. + * @throws \BernardLedit\Pdf\PdfiumException if `PDFium` can't read the page's text. + * @throws \Exception if the document is closed. */ public function getText(): string {} /** - * Checks whether the entire document is empty. + * Checks whether the page is empty. * * @return bool - * @throws \Exception Returns a PHP Exception if the `PdfDocument` is inaccessible. + * @throws \BernardLedit\Pdf\PdfiumException if `PDFium` can't read the page. + * @throws \Exception if the document is closed. */ public function isEmpty(): bool {} /** - * Renders the page. + * Renders the page, at 72 DPI per unit of `$scale`. * - * @param float $scale - * @return \PdfBitmap - * @throws \Exception Returns a PHP Exception if the `PdfDocument` is inaccessible. + * @param float $scale A finite number between 0.01 and 16. + * @return \BernardLedit\Pdf\PdfBitmap + * @throws \ValueError if `$scale` is out of range. + * @throws \BernardLedit\Pdf\PdfiumException if `PDFium` can't render the page. + * @throws \Exception if the document is closed. */ - public function renderToBitmap(float $scale = 1.0): \PdfBitmap {} + public function renderToBitmap(float $scale = 1.0): \BernardLedit\Pdf\PdfBitmap {} } - class PdfiumException extends \Exception { - public function __construct() {} + /** + * Text character representation. + */ + class TextChar { + /** + * @param string $char Only the first character is kept; `" "` if empty. + * @param string $font_name + * @param float $font_size + * @param int<0, 4294967295> $font_weight + * @param array{int<0, 255>, int<0, 255>, int<0, 255>, int<0, 255>}|null $stroke_color RGBA. + * @param array{int<0, 255>, int<0, 255>, int<0, 255>, int<0, 255>}|null $fill_color RGBA. + * @param int<-2147483648, 2147483647> $font_flags + * @param array{float, float, float, float}|null $bounds Zeros if `null`. + * @throws \ValueError if `$font_weight` or `$font_flags` is out of range, or `$stroke_color`, `$fill_color` or `$bounds` doesn't have 4 values, or a color value is out of range. + */ + public function __construct(string $char, string $font_name, float $font_size, int $font_weight, ?array $stroke_color, ?array $fill_color, int $font_flags, ?array $bounds = null) {} + + /** + * Default debug info. + * + * @return array + */ + public function __debugInfo(): array {} + + /** + * String rep. + * + * @return string + */ + public function __toString(): string {} } /** - * Keeps or removes pages. Negative indexes count from the end./// + * Keeps or removes pages, if the PDF has at least `$on_min_pages` pages. Negative indexes count + * from the end, and indexes past the end are skipped. * * @param string $data - * @param string $operation - * @param int $on_min_pages - * @param array $page_indexes - * @return array - * @throws \Exception Throws a [`ValueError`] if one or more of the provided values is incorrect. + * @param string $operation `KEEP_ONLY` or `REMOVE`, case-insensitive. + * @param int<0, 4294967295> $on_min_pages + * @param list> $page_indexes + * @return array{0: \BernardLedit\Pdf\PdfDocument|null, 1: list} The new document, or `null` if the PDF has fewer than `$on_min_pages` pages; and the skipped indexes. + * @throws \ValueError if `$on_min_pages` or an index is out of range, `$operation` isn't `KEEP_ONLY` or `REMOVE`, the PDF has no content, or no pages would be left. + * @throws \BernardLedit\Pdf\PdfiumException if `PDFium` can't be loaded, `$data` isn't a PDF it can read, or it can't build the new document. */ function applyPageOptions(string $data, string $operation, int $on_min_pages, array $page_indexes): array {} @@ -348,25 +417,26 @@ function applyPageOptions(string $data, string $operation, int $on_min_pages, ar * Compresses PDF bytes. Returns the input unchanged if it can't be made smaller. * * @param string $data - * @param int $quality - * @param bool|null $optimize - * @param float|null $dpi + * @param int<5, 100> $quality + * @param bool|null $optimize Whether to optimize JPEG Huffman tables; defaults to `true`. + * @param float|null $dpi A finite number between 1 and 1200; 150 if `null`. * @return string - * @throws \Exception Returns a PHP Exception if the PDF is invalid or compression fails. + * @throws \ValueError if `$quality` or `$dpi` is out of range. + * @throws \BernardLedit\Image\ImageException if JPEG encoding fails. + * @throws \BernardLedit\Pdf\PdfiumException if `PDFium` can't be loaded, `$data` isn't a PDF it can read, or it can't render a page or build the new document. */ - function compress(string $data, int $quality = 85, ?bool $optimize = null, ?float $dpi = null): string {} + function compressToJpeg(string $data, int $quality = 85, ?bool $optimize = null, ?float $dpi = null): string {} /** * Builds one new document per group of 0-indexed page numbers. * `data` is a PDF or an image (treated as a one-page document). * * @param string $data - * @param array $page_indexes - * @return array - * @throws \Exception Throws if no groups are given. - * @throws \Exception Throws if a group is empty. - * @throws \Exception Throws if a page index is out of range. - * @throws \Exception Throws if the data is neither a valid PDF nor a supported image. + * @param non-empty-list>> $page_indexes + * @return list<\BernardLedit\Pdf\PdfDocument> One document per group, in the same order. + * @throws \ValueError if an index is out of range, `$page_indexes` or one of its groups is empty, or there's no page at one of the indexes. + * @throws \BernardLedit\Image\ImageException if `$data` is neither a PDF nor an identifiable, decodable image. + * @throws \BernardLedit\Pdf\PdfiumException if `PDFium` can't be loaded, `$data` is a PDF it can't read, or it can't build the documents. */ function extractFromPageRanges(string $data, array $page_indexes): array {} @@ -374,94 +444,23 @@ function extractFromPageRanges(string $data, array $page_indexes): array {} * Drops every byte before the first `%PDF-` marker. * * @param string $data - * @param int $maximum_offset + * @param int<0, max> $maximum_offset How far into `$data` to look for the marker, in bytes. * @return string - * @throws \Exception Throws a [`ValueError`] if there is no marker before `$maximumOffset`. + * @throws \ValueError if `$maximum_offset` is negative, or there's no marker before it. */ function fixPdf(string $data, int $maximum_offset = 500): string {} } -namespace { - class PdfBitmap { - public function __construct() {} - - /** - * Debug info. - * - * @return array - */ - public function __debugInfo(): array {} - - /** - * String rep. - * - * @return string - */ - public function __toString(): string {} - - /** - * Height in pixels. - * - * @return int - */ - public function getHeight(): int {} - - /** - * Width in pixels. - * - * @return int - */ - public function getWidth(): int {} - - /** - * Raw RGBA8 pixel buffer (row-major, 4 bytes per pixel). - * - * @return string - */ - public function toBytes(): string {} - - /** - * Encode the bitmap as a PNG byte stream. - * - * @return string - * @throws \Exception Returns a PHP Exception if the conversion fails. - */ - public function toPngBytes(): string {} - } - +namespace BernardLedit\Image { /** - * Text character representation. + * Input that isn't an identifiable or decodable image, and encoding failures. */ - class TextChar { - /** - * Create a new text character. - * - * @param string $char - * @param string $font_name - * @param float $font_size - * @param int $font_weight - * @param array|null $stroke_color - * @param array|null $fill_color - * @param int $font_flags - * @param array|null $bounds - * @throws \Exception Throws a `ValueError` if `stroke_color` or `fill_color` is provided - * @throws \Exception with a length other than 4, or if `bounds` is provided with a length - * @throws \Exception other than 4. - */ - public function __construct(string $char, string $font_name, float $font_size, int $font_weight, ?array $stroke_color, ?array $fill_color, int $font_flags, ?array $bounds = null) {} - - /** - * Default debug info. - * - * @return array - */ - public function __debugInfo(): array {} + class ImageException extends \Exception {} +} - /** - * String rep. - * - * @return string - */ - public function __toString(): string {} - } +namespace BernardLedit\Pdf { + /** + * `PDFium` can't be loaded, or fails to read, render or write a document. + */ + class PdfiumException extends \Exception {} } diff --git a/tests/Input/LocalInputSourceTest.php b/tests/Input/LocalInputSourceTest.php index 7de67da9..86364a74 100644 --- a/tests/Input/LocalInputSourceTest.php +++ b/tests/Input/LocalInputSourceTest.php @@ -106,8 +106,8 @@ public function testPdfCutNPages(array $indexes): void self::assertSame($cutPdf->getPageCount(), $basePdf->getPageCount()); for ($pageNumber = 0; $pageNumber < $cutPdf->getPageCount(); $pageNumber++) { self::assertSame( - $cutPdf->rasterizePageToJpegBytes($pageNumber, 100), - $basePdf->rasterizePageToJpegBytes($pageNumber, 100), + $cutPdf->rasterizePage($pageNumber)->encode('JPEG', 100), + $basePdf->rasterizePage($pageNumber)->encode('JPEG', 100), "Page $pageNumber differs from the reference cut PDF." ); } From 4c0a6aba3a4923c8925f8a85d407b26fc91a7ade Mon Sep 17 00:00:00 2001 From: Bashir ABDEL WAHED Date: Fri, 13 Nov 2026 00:43:18 +0100 Subject: [PATCH 2/8] Remove PdfPage size from extension stubs Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- stubs/bernard_ledit.stubs.php | 9 --------- 1 file changed, 9 deletions(-) diff --git a/stubs/bernard_ledit.stubs.php b/stubs/bernard_ledit.stubs.php index 8554bd92..30ce76b3 100644 --- a/stubs/bernard_ledit.stubs.php +++ b/stubs/bernard_ledit.stubs.php @@ -328,15 +328,6 @@ public function getChars(): array {} */ public function getIndex(): int {} - /** - * Dimensions in points. - * - * @return array{0: float, 1: float} `[$width, $height]`. - * @throws \BernardLedit\Pdf\PdfiumException if `PDFium` can't load the page. - * @throws \Exception if the document is closed. - */ - public function getSize(): array {} - /** * Returns the text of the page. * From d7a4897863a92f0b03b18e3a31e7d3fca1d7da05 Mon Sep 17 00:00:00 2001 From: Bashir ABDEL WAHED Date: Fri, 13 Nov 2026 00:43:47 +0100 Subject: [PATCH 3/8] Remove PdfPage isEmpty from extension stubs Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- stubs/bernard_ledit.stubs.php | 9 --------- 1 file changed, 9 deletions(-) diff --git a/stubs/bernard_ledit.stubs.php b/stubs/bernard_ledit.stubs.php index 30ce76b3..e0bb1b81 100644 --- a/stubs/bernard_ledit.stubs.php +++ b/stubs/bernard_ledit.stubs.php @@ -337,15 +337,6 @@ public function getIndex(): int {} */ public function getText(): string {} - /** - * Checks whether the page is empty. - * - * @return bool - * @throws \BernardLedit\Pdf\PdfiumException if `PDFium` can't read the page. - * @throws \Exception if the document is closed. - */ - public function isEmpty(): bool {} - /** * Renders the page, at 72 DPI per unit of `$scale`. * From 9685cb50da9e2c8f883cc8199ec7ea7ff8cdea15 Mon Sep 17 00:00:00 2001 From: Bashir ABDEL WAHED Date: Fri, 13 Nov 2026 00:44:32 +0100 Subject: [PATCH 4/8] Remove PdfPage getChars from extension stubs Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- stubs/bernard_ledit.stubs.php | 9 --------- 1 file changed, 9 deletions(-) diff --git a/stubs/bernard_ledit.stubs.php b/stubs/bernard_ledit.stubs.php index e0bb1b81..e71d21a0 100644 --- a/stubs/bernard_ledit.stubs.php +++ b/stubs/bernard_ledit.stubs.php @@ -312,15 +312,6 @@ public function rasterizePage(int $index): \BernardLedit\Image\Image {} class PdfPage { public function __construct() {} - /** - * Returns the characters on the page. - * - * @return list<\BernardLedit\Pdf\TextChar> - * @throws \BernardLedit\Pdf\PdfiumException if `PDFium` can't read the page's characters. - * @throws \Exception if the document is closed. - */ - public function getChars(): array {} - /** * Index of the page. * From 839a2c6c725cb6cab6ed9200ae6b55965aaae736 Mon Sep 17 00:00:00 2001 From: Bashir ABDEL WAHED Date: Fri, 13 Nov 2026 00:47:38 +0100 Subject: [PATCH 5/8] Remove JPEG page append methods from extension stubs Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- stubs/bernard_ledit.stubs.php | 22 ---------------------- 1 file changed, 22 deletions(-) diff --git a/stubs/bernard_ledit.stubs.php b/stubs/bernard_ledit.stubs.php index e71d21a0..7568686f 100644 --- a/stubs/bernard_ledit.stubs.php +++ b/stubs/bernard_ledit.stubs.php @@ -177,28 +177,6 @@ class PdfDocument { */ public function __construct(string $data) {} - /** - * Appends a JPEG as a page of the document. - * - * @param string $jpeg - * @return void - * @throws \BernardLedit\Image\ImageException if `$jpeg` is invalid, truncated or in an unsupported color space. - * @throws \BernardLedit\Pdf\PdfiumException if `PDFium` can't append the page. - * @throws \Exception if the document is closed. - */ - public function appendJpegPage(string $jpeg): void {} - - /** - * Append multiple JPEG pages to the document. - * - * @param list $jpegs - * @return void - * @throws \BernardLedit\Image\ImageException if one of `$jpegs` is invalid, truncated or in an unsupported color space. - * @throws \BernardLedit\Pdf\PdfiumException if `PDFium` can't append a page. - * @throws \Exception if the document is closed. - */ - public function appendMultipleJpegPages(array $jpegs): void {} - /** * Returns the PDF bytes (PHP writes files itself and keeps I/O out of Rust). * From fec6db01b4f26d527773d5ade400cd75bb4b2d97 Mon Sep 17 00:00:00 2001 From: Bashir ABDEL WAHED Date: Fri, 13 Nov 2026 02:47:36 +0100 Subject: [PATCH 6/8] Use shared format inference for extracted files Use the common Bernard Ledit helper when saving extracted images and PDFs. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/Image/ExtractedImage.php | 24 +++---------- src/Image/ImageExtractor.php | 6 ++-- src/Pdf/ExtractedPdf.php | 3 +- stubs/bernard_ledit.stubs.php | 64 ++++++++--------------------------- 4 files changed, 24 insertions(+), 73 deletions(-) diff --git a/src/Image/ExtractedImage.php b/src/Image/ExtractedImage.php index d8c8c717..ef58c275 100644 --- a/src/Image/ExtractedImage.php +++ b/src/Image/ExtractedImage.php @@ -12,6 +12,7 @@ use Exception; use function BernardLedit\Image\decode; +use function BernardLedit\Common\formatFromExtension; use function sprintf; use function strlen; @@ -52,8 +53,10 @@ public function __construct(public string $buffer, public string $filename, prot public function writeToFile(string $outputPath, ?string $format = null, ?int $quality = null): void { $imagePath = $outputPath . DIRECTORY_SEPARATOR . $this->filename; - $encodedFormat = self::getEncodedImageFormat($format ?? $this->saveFormat); - if (null === $quality && $encodedFormat === self::getEncodedImageFormat($this->saveFormat)) { + $extension = pathinfo($this->filename, PATHINFO_EXTENSION); + $formatToEncode = $format ?? ('' !== $extension ? $extension : $this->saveFormat); + $encodedFormat = formatFromExtension($formatToEncode); + if (null === $quality && $encodedFormat === formatFromExtension($this->saveFormat)) { self::writeBytes($imagePath, $this->buffer); return; } @@ -71,23 +74,6 @@ public function asInputSource(): BytesInput return new BytesInput($this->buffer, $this->filename); } - /** - * Get the encoded image format, as understood by bernard_ledit. - * - * @param string $saveFormat Format to save the file as. - * @return string Encoded image format. - */ - public static function getEncodedImageFormat(string $saveFormat): string - { - return match (strtolower($saveFormat)) { - 'png' => 'png', - 'bmp', => 'bmp', - 'gif' => 'gif', - 'webp' => 'webp', - default => 'jpeg', - }; - } - /** * Writes bytes to a file, and fails if they weren't all written. * diff --git a/src/Image/ImageExtractor.php b/src/Image/ImageExtractor.php index 69418158..f02bbd04 100644 --- a/src/Image/ImageExtractor.php +++ b/src/Image/ImageExtractor.php @@ -19,6 +19,7 @@ use Mindee\Pdf\PdfUtils; use ValueError; +use function BernardLedit\Common\formatFromExtension; use function BernardLedit\Image\guessFormat; use function count; use function sprintf; @@ -206,8 +207,7 @@ protected function cropPolygons(array $polygons, int $pageIndex): array if ($this->inputSource->isPdf()) { $pdf = new PdfDocument($this->sourceData); try { - $bitmap = $pdf->getPage($pageIndex)->renderToBitmap($this->pdfDpi / 72.0); - $sourceImage = new Image($bitmap->toPngBytes()); + $sourceImage = $pdf->getPage($pageIndex)->render($this->pdfDpi / 72.0); } finally { PdfUtils::closeQuietly($pdf); } @@ -237,7 +237,7 @@ protected function encodeCrop( string $format ): ExtractedImage { try { - $data = $crop->encode(ExtractedImage::getEncodedImageFormat($format), self::CROP_QUALITY); + $data = $crop->encode(formatFromExtension($format), self::CROP_QUALITY); } catch (ImageException|ValueError $e) { throw new MindeeImageException($e->getMessage(), $e->getCode(), $e); } diff --git a/src/Pdf/ExtractedPdf.php b/src/Pdf/ExtractedPdf.php index e99a8573..f567f527 100644 --- a/src/Pdf/ExtractedPdf.php +++ b/src/Pdf/ExtractedPdf.php @@ -11,6 +11,7 @@ use Mindee\Error\MindeePdfException; use Mindee\Error\MindeeUnhandledException; use Mindee\Input\BytesInput; +use function BernardLedit\Common\formatFromExtension; use const DIRECTORY_SEPARATOR; @@ -71,7 +72,7 @@ public function writeToFile(string $outputPath): void $pdfPath = $outputPath; } } - if (!str_ends_with(strtolower($pdfPath), 'pdf')) { + if ('PDF' !== formatFromExtension(pathinfo($pdfPath, PATHINFO_EXTENSION))) { $pdfPath .= '.pdf'; } file_put_contents($pdfPath, $this->pdfBytes); diff --git a/stubs/bernard_ledit.stubs.php b/stubs/bernard_ledit.stubs.php index 7568686f..5f874ee3 100644 --- a/stubs/bernard_ledit.stubs.php +++ b/stubs/bernard_ledit.stubs.php @@ -3,6 +3,16 @@ // Stubs for bernard_ledit +namespace BernardLedit\Common { + /** + * Returns the canonical encoding name for a file extension. + * + * @param string $extension + * @return string + */ + function formatFromExtension(string $extension): string {} +} + namespace BernardLedit\Image { class Image { /** @@ -118,56 +128,10 @@ function decode(string $data): \BernardLedit\Image\Image {} * @throws \BernardLedit\Image\ImageException if `$data` isn't an identifiable image. */ function guessFormat(string $data): string {} + } namespace BernardLedit\Pdf { - class PdfBitmap { - public function __construct() {} - - /** - * Debug info. - * - * @return array - */ - public function __debugInfo(): array {} - - /** - * String rep. - * - * @return string - */ - public function __toString(): string {} - - /** - * Height in pixels. - * - * @return int - */ - public function getHeight(): int {} - - /** - * Width in pixels. - * - * @return int - */ - public function getWidth(): int {} - - /** - * Raw RGBA8 pixel buffer (row-major, 4 bytes per pixel). - * - * @return string - */ - public function toBytes(): string {} - - /** - * Encode the bitmap as a PNG byte stream. - * - * @return string - * @throws \BernardLedit\Image\ImageException if PNG encoding fails. - */ - public function toPngBytes(): string {} - } - class PdfDocument { /** * Create a new instance from bytes. @@ -307,15 +271,15 @@ public function getIndex(): int {} public function getText(): string {} /** - * Renders the page, at 72 DPI per unit of `$scale`. + * Renders the page as an image, at 72 DPI per unit of `$scale`. * * @param float $scale A finite number between 0.01 and 16. - * @return \BernardLedit\Pdf\PdfBitmap + * @return \BernardLedit\Image\Image * @throws \ValueError if `$scale` is out of range. * @throws \BernardLedit\Pdf\PdfiumException if `PDFium` can't render the page. * @throws \Exception if the document is closed. */ - public function renderToBitmap(float $scale = 1.0): \BernardLedit\Pdf\PdfBitmap {} + public function render(float $scale = 1.0): \BernardLedit\Image\Image {} } /** From 0e59ca4dacce3ec8ac02169a40987fb0b1030422 Mon Sep 17 00:00:00 2001 From: Bashir ABDEL WAHED Date: Fri, 13 Nov 2026 02:56:59 +0100 Subject: [PATCH 7/8] Render PDF pages through the page API Remove rasterizePage from the extension stub and update tests to use getPage()->render(). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- stubs/bernard_ledit.stubs.php | 10 ---------- tests/Input/LocalInputSourceTest.php | 4 ++-- 2 files changed, 2 insertions(+), 12 deletions(-) diff --git a/stubs/bernard_ledit.stubs.php b/stubs/bernard_ledit.stubs.php index 5f874ee3..96c154b3 100644 --- a/stubs/bernard_ledit.stubs.php +++ b/stubs/bernard_ledit.stubs.php @@ -239,16 +239,6 @@ public function hasText(): bool {} */ public function importPages(\BernardLedit\Pdf\PdfDocument $src, array $indexes): void {} - /** - * Rasterizes a page from a given index into an image, at 72 DPI. - * - * @param int<0, 65535> $index - * @return \BernardLedit\Image\Image - * @throws \ValueError if `$index` is out of range, or there's no page `$index`. - * @throws \BernardLedit\Pdf\PdfiumException if `PDFium` can't render the page. - * @throws \Exception if the document is closed. - */ - public function rasterizePage(int $index): \BernardLedit\Image\Image {} } class PdfPage { diff --git a/tests/Input/LocalInputSourceTest.php b/tests/Input/LocalInputSourceTest.php index 86364a74..95eec4d5 100644 --- a/tests/Input/LocalInputSourceTest.php +++ b/tests/Input/LocalInputSourceTest.php @@ -106,8 +106,8 @@ public function testPdfCutNPages(array $indexes): void self::assertSame($cutPdf->getPageCount(), $basePdf->getPageCount()); for ($pageNumber = 0; $pageNumber < $cutPdf->getPageCount(); $pageNumber++) { self::assertSame( - $cutPdf->rasterizePage($pageNumber)->encode('JPEG', 100), - $basePdf->rasterizePage($pageNumber)->encode('JPEG', 100), + $cutPdf->getPage($pageNumber)->render()->encode('JPEG', 100), + $basePdf->getPage($pageNumber)->render()->encode('JPEG', 100), "Page $pageNumber differs from the reference cut PDF." ); } From 52616bf7d4d90eda0c08740a1b3676625c338a79 Mon Sep 17 00:00:00 2001 From: Bashir ABDEL WAHED Date: Fri, 13 Nov 2026 03:12:56 +0100 Subject: [PATCH 8/8] Use toBytes for PDF serialization Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/Input/LocalInputSource.php | 2 +- src/Pdf/PdfExtractor.php | 2 +- stubs/bernard_ledit.stubs.php | 10 +++++++++- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/Input/LocalInputSource.php b/src/Input/LocalInputSource.php index a230a63d..5e5cc25a 100644 --- a/src/Input/LocalInputSource.php +++ b/src/Input/LocalInputSource.php @@ -353,7 +353,7 @@ public function applyPageOptions(?PageOptions $pageOptions): void return; } try { - $documentBytes = $document->asBytes(); + $documentBytes = $document->toBytes(); $this->saveBytesAsFile($documentBytes); $this->pageCount = $document->getPageCount(); } catch (Exception $e) { diff --git a/src/Pdf/PdfExtractor.php b/src/Pdf/PdfExtractor.php index 17e7f9c7..61790261 100644 --- a/src/Pdf/PdfExtractor.php +++ b/src/Pdf/PdfExtractor.php @@ -123,7 +123,7 @@ private static function buildSubDocument(PdfDocument $source, array $pageIndexes try { $subPdf = PdfDocument::create(); $subPdf->importPages($source, array_values($pageIndexes)); - return $subPdf->asBytes(); + return $subPdf->toBytes(); } catch (Exception $e) { throw new MindeePdfException( "PDF file couldn't be processed during extraction.", diff --git a/stubs/bernard_ledit.stubs.php b/stubs/bernard_ledit.stubs.php index 96c154b3..8c8e8595 100644 --- a/stubs/bernard_ledit.stubs.php +++ b/stubs/bernard_ledit.stubs.php @@ -95,6 +95,14 @@ public function getWidth(): int {} * @throws \ValueError if `$width` or `$height` is out of range. */ public function resize(int $width, int $height): \BernardLedit\Image\Image {} + + /** + * Returns the image bytes. + * + * @return string + * @throws \BernardLedit\Image\ImageException if the image bytes can't be retrieved. + */ + public function toBytes(): string {} } /** @@ -148,7 +156,7 @@ public function __construct(string $data) {} * @throws \BernardLedit\Pdf\PdfiumException if `PDFium` can't save the document. * @throws \Exception if the document is closed. */ - public function asBytes(): string {} + public function toBytes(): string {} /** * Close the document. Closing it again does nothing.