Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,21 @@ All notable changes to `dskripchenko/php-pdf` are documented in this file.
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/);
versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [1.28.0] — 2026-11-14

### Added
- `ReaderDocument::text()` extracts the plain text of a PDF:
`Pdf\Reader\Text\TextExtractor` interprets the text operators of each
page and the form XObjects it draws; `FontDecoder` turns codes into text
through `/ToUnicode` maps (`ToUnicodeMap`: code space, `bfchar`, `bfrange`
with arrays), simple-font encodings (`SimpleEncodings`: Standard,
WinAnsi, MacRoman) and `/Differences` named by the Adobe Glyph List
(`GlyphNames`: the Latin set, `uniXXXX`, `uXXXX`, Cyrillic `afii`,
ligatures with `_`); widths from `/Widths` and `/W` place the glyphs, so
lines and word spaces follow the page. Typographic ligatures are written
out. Inline images are skipped; a broken stream gives the text read up to
the break.

## [1.27.0] — 2026-11-09

### Added
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,9 @@ file_put_contents('hello.pdf', $doc->toBytes());
### Reading and merging
- Read existing PDFs (`ReaderDocument`) — classic and stream xref, object
streams, corrupt-xref recovery, decryption (RC4 / AES-128 / AES-256).
- Extract plain text (`ReaderDocument::text()`) — ToUnicode maps, simple-font
encodings with `/Differences`, composite fonts, form XObjects; lines and
word spaces from glyph positions.
- Merge (`PdfMerger`) — append and reorder whole or selected pages from
multiple files; page annotations and bookmarks carried over with internal
links and named destinations remapped.
Expand Down
18 changes: 18 additions & 0 deletions docs/de/MERGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ Alles in reinem PHP und MIT-lizenziert — kein FPDI, keine externen Binaries.
## Inhalt

- [Ein PDF lesen](#ein-pdf-lesen)
- [Text extrahieren](#text-extrahieren)
- [Dokumente anhängen](#dokumente-anhängen)
- [Seiten auswählen und umordnen](#seiten-auswählen-und-umordnen)
- [Eine Seite einbetten (stempeln)](#eine-seite-einbetten-stempeln)
Expand Down Expand Up @@ -37,6 +38,23 @@ Ein `ReaderDocument` löst Objekte lazy auf, folgt der Querverweiskette
(klassische Tabellen, XRef-Streams und Objekt-Streams) und fällt auf einen
vollständigen Datei-Scan zurück, wenn die Querverweise beschädigt sind.

## Text extrahieren

```php
$doc = ReaderDocument::fromBytes(file_get_contents('report.pdf'));
echo $doc->text(); // alle Seiten, getrennt durch eine Leerzeile
```

Der Text jeder Glyphe kommt aus ihrer Schrift: zuerst die `/ToUnicode`-Tabelle,
dann die Kodierung der einfachen Schrift (Standard, WinAnsi, MacRoman) mit
`/Differences` nach den Namen der Adobe Glyph List (einschließlich der
kyrillischen `afii`-Namen und `uniXXXX`). Gelesen wird in Inhaltsreihenfolge;
ein Wechsel in eine andere Zeile beginnt eine neue Zeile, eine Lücke breiter
als ein Fünftel der Schriftgröße wird zum Leerzeichen, Ligaturen werden
ausgeschrieben (`fi` → `fi`). Form-XObjects werden mitgelesen. Ein Scan hat
keinen Text — es gibt keine Texterkennung —, und eine zusammengesetzte
Schrift ohne `/ToUnicode`-Tabelle liefert für ihre Glyphen nichts.

## Dokumente anhängen

`PdfMerger` verkettet Seiten aus einer oder mehreren Quellen zu einem neuen
Expand Down
3 changes: 3 additions & 0 deletions docs/de/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,9 @@ file_put_contents('hello.pdf', $doc->toBytes());
- Bestehende PDFs lesen (`ReaderDocument`) — klassische und Stream-xref,
Objekt-Streams, Wiederherstellung bei beschädigter xref, Entschlüsselung
(RC4 / AES-128 / AES-256).
- Text extrahieren (`ReaderDocument::text()`) — ToUnicode-Tabellen,
Kodierungen einfacher Schriften mit `/Differences`, zusammengesetzte
Schriften, Form-XObjects; Zeilen und Wortabstände aus den Glyphpositionen.
- Zusammenführen (`PdfMerger`) — ganze oder ausgewählte Seiten aus mehreren
Dateien anhängen und umordnen; Seitenannotationen und Lesezeichen werden
mit umgemappten internen Links und benannten Zielen übernommen.
Expand Down
17 changes: 17 additions & 0 deletions docs/en/MERGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ All of it is pure PHP and MIT-licensed — no FPDI, no external binaries.
## Contents

- [Reading a PDF](#reading-a-pdf)
- [Extracting text](#extracting-text)
- [Appending documents](#appending-documents)
- [Selecting and reordering pages](#selecting-and-reordering-pages)
- [Embedding (stamping) a page](#embedding-stamping-a-page)
Expand Down Expand Up @@ -36,6 +37,22 @@ A `ReaderDocument` resolves objects lazily, follows the cross-reference chain
(classic tables, XRef streams, and object streams), and falls back to a
full-file scan when the cross-reference is corrupt.

## Extracting text

```php
$doc = ReaderDocument::fromBytes(file_get_contents('report.pdf'));
echo $doc->text(); // every page, pages separated by a blank line
```

Each glyph's text comes from its font: the `/ToUnicode` map first, then the
simple font's encoding (Standard, WinAnsi, MacRoman) with `/Differences`
named by the Adobe Glyph List (Cyrillic `afii` names, `uniXXXX` included).
Text is read in content order; a move to another line starts a new line, a
gap wider than a fifth of the font size becomes a space, and typographic
ligatures are written out (`fi` → `fi`). Form XObjects are read too. A scan
has no text to give — there is no OCR — and a composite font without a
`/ToUnicode` map gives nothing for its glyphs.

## Appending documents

`PdfMerger` concatenates pages from one or more sources into a new document
Expand Down
17 changes: 17 additions & 0 deletions docs/ru/MERGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ PDF-файлы** и **комбинировать** их: присоединят
## Содержание

- [Чтение PDF](#чтение-pdf)
- [Извлечение текста](#извлечение-текста)
- [Присоединение документов](#присоединение-документов)
- [Выбор и переупорядочивание страниц](#выбор-и-переупорядочивание-страниц)
- [Встраивание (штамп) страницы](#встраивание-штамп-страницы)
Expand Down Expand Up @@ -37,6 +38,22 @@ foreach ($doc->pages() as $page) {
(классические таблицы, XRef-потоки и object-потоки) и переходит к полному скану
файла, если xref повреждён.

## Извлечение текста

```php
$doc = ReaderDocument::fromBytes(file_get_contents('report.pdf'));
echo $doc->text(); // все страницы, между страницами — пустая строка
```

Текст каждого глифа берётся из его шрифта: сначала карта `/ToUnicode`, затем
кодировка простого шрифта (Standard, WinAnsi, MacRoman) с `/Differences` по
именам Adobe Glyph List (включая кириллические `afii` и `uniXXXX`). Текст
читается в порядке содержимого; переход на другую строку начинает новую
строку, промежуток шире пятой части кегля становится пробелом, лигатуры
раскрываются (`fi` → `fi`). Form XObject тоже читаются. У скана текста нет —
распознавания нет, — а составной шрифт без карты `/ToUnicode` не даёт текста
своих глифов.

## Присоединение документов

`PdfMerger` склеивает страницы из одного или нескольких источников в новый
Expand Down
3 changes: 3 additions & 0 deletions docs/ru/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,9 @@ file_put_contents('hello.pdf', $doc->toBytes());
### Чтение и объединение
- Чтение готовых PDF (`ReaderDocument`) — классический и потоковый xref,
object-потоки, восстановление битого xref, расшифровка (RC4 / AES-128 / AES-256).
- Извлечение текста (`ReaderDocument::text()`) — карты ToUnicode, кодировки
простых шрифтов с `/Differences`, составные шрифты, form XObject; строки и
пробелы — по положению глифов.
- Объединение (`PdfMerger`) — склейка и переупорядочивание всех или выбранных
страниц из нескольких файлов; аннотации страниц и закладки переносятся с
ремапом внутренних ссылок и именованных назначений.
Expand Down
10 changes: 10 additions & 0 deletions docs/zh/MERGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
## 目录

- [读取 PDF](#读取-pdf)
- [提取文本](#提取文本)
- [追加文档](#追加文档)
- [选择与重排页面](#选择与重排页面)
- [嵌入(盖印)页面](#嵌入盖印页面)
Expand All @@ -35,6 +36,15 @@ foreach ($doc->pages() as $page) {
`ReaderDocument` 惰性解析对象,沿交叉引用链(经典表、XRef 流和对象流)遍历,
并在交叉引用损坏时回退到整文件扫描。

## 提取文本

```php
$doc = ReaderDocument::fromBytes(file_get_contents('report.pdf'));
echo $doc->text(); // 所有页面,页面之间以空行分隔
```

每个字形的文本来自其字体:先查 `/ToUnicode` 映射,再按简单字体的编码(Standard、WinAnsi、MacRoman)及按 Adobe Glyph List 命名的 `/Differences`(包括西里尔 `afii` 名称和 `uniXXXX`)。文本按内容顺序读取;换到另一行时开始新行,宽于字号五分之一的间隙变为空格,排版连字会展开(`fi` → `fi`)。表单 XObject 也会读取。扫描件没有文本可提取——不做 OCR;没有 `/ToUnicode` 映射的复合字体不会给出其字形的文本。

## 追加文档

`PdfMerger` 将一个或多个来源的页面连接成一个新文档(pdftk 风格):
Expand Down
1 change: 1 addition & 0 deletions docs/zh/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,7 @@ file_put_contents('hello.pdf', $doc->toBytes());
### 读取与合并
- 读取现有 PDF(`ReaderDocument`)—— 经典与流式 xref、对象流、损坏 xref 恢复、
解密(RC4 / AES-128 / AES-256)。
- 提取纯文本(`ReaderDocument::text()`)—— ToUnicode 映射、带 `/Differences` 的简单字体编码、复合字体、表单 XObject;按字形位置划分行与词间空格。
- 合并(`PdfMerger`)—— 追加并重排来自多个文件的全部或选定页面;页面注释与书签
会被带入,内部链接和命名目标随之重新映射。
- 盖印叠加(水印、信头)与 FPDI 风格的页面导入,通过
Expand Down
9 changes: 9 additions & 0 deletions src/Pdf/Reader/ReaderDocument.php
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,15 @@ public function streamData(PdfStream $stream): string
return (new StreamDecoder($this))->decode($stream);
}

/**
* The document's plain text, pages separated by a blank line (§9.10):
* what its fonts say the shown glyphs are, in content order.
*/
public function text(): string
{
return (new Text\TextExtractor($this))->document();
}

/**
* The document catalog (`/Root`).
*/
Expand Down
188 changes: 188 additions & 0 deletions src/Pdf/Reader/Text/FontDecoder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
<?php

declare(strict_types=1);

namespace Dskripchenko\PhpPdf\Pdf\Reader\Text;

use Dskripchenko\PhpPdf\Pdf\Reader\PdfDictionary;
use Dskripchenko\PhpPdf\Pdf\Reader\PdfName;
use Dskripchenko\PhpPdf\Pdf\Reader\PdfStream;
use Dskripchenko\PhpPdf\Pdf\Reader\ReaderDocument;
use Throwable;

/**
* What the bytes of a shown string mean in one font (§9.4.3, §9.10): codes
* split by the font's code length, each code's text — from /ToUnicode, else
* from the simple font's encoding and /Differences — and its advance width
* in thousandths of the font size.
*/
final class FontDecoder
{
private ?ToUnicodeMap $toUnicode = null;

/** @var array<int,string> one-byte code → text, simple fonts */
private array $encoding = [];

/** @var array<int,float> code → width */
private array $widths = [];

private float $defaultWidth = 500.0;

/** Thousandths per glyph space unit: 1 except for Type 3 fonts. */
private float $scale = 1.0;

private bool $composite = false;

public static function fromDictionary(ReaderDocument $doc, PdfDictionary $font): self
{
$decoder = new self();
$subtype = self::name($doc->deref($font->get('Subtype')));
$toUnicode = $doc->deref($font->get('ToUnicode'));
if ($toUnicode instanceof PdfStream) {
try {
$map = ToUnicodeMap::parse($doc->streamData($toUnicode));
$decoder->toUnicode = $map->isEmpty() ? null : $map;
} catch (Throwable) {
$decoder->toUnicode = null;
}
}
if ($subtype === 'Type0') {
$decoder->composite = true;
$decoder->defaultWidth = 1000.0;
$descendants = $doc->deref($font->get('DescendantFonts'));
$cid = is_array($descendants) ? $doc->deref($descendants[0] ?? null) : null;
if ($cid instanceof PdfDictionary) {
$decoder->cidWidths($doc, $cid);
}

return $decoder;
}
$decoder->simpleEncoding($doc, $font, $subtype);
$decoder->simpleWidths($doc, $font);
if ($subtype === 'Type3') {
$matrix = $doc->deref($font->get('FontMatrix'));
$a = is_array($matrix) ? $doc->deref($matrix[0] ?? null) : null;
$decoder->scale = is_int($a) || is_float($a) ? (float) $a * 1000.0 : 1.0;
}

return $decoder;
}

/**
* The codes of a string: each code's text (empty when unknown), width and
* whether it is the single-byte space that word spacing applies to.
*
* @return list<array{string,float,bool}>
*/
public function decode(string $bytes): array
{
$out = [];
$length = strlen($bytes);
$i = 0;
while ($i < $length) {
$n = $this->toUnicode?->codeLength($bytes, $i) ?? ($this->composite ? 2 : 1);
$code = substr($bytes, $i, $n);
$i += $n;
$number = 0;
foreach (str_split($code) as $byte) {
$number = ($number << 8) | ord($byte);
}
$text = $this->toUnicode?->lookup($code);
if ($text === null && !$this->composite) {
$text = $this->encoding[$number] ?? '';
}
$out[] = [$text ?? '', ($this->widths[$number] ?? $this->defaultWidth) * $this->scale, $n === 1 && $number === 32];
}

return $out;
}

private function simpleEncoding(ReaderDocument $doc, PdfDictionary $font, ?string $subtype): void
{
$encoding = $doc->deref($font->get('Encoding'));
$base = $subtype === 'TrueType' ? 'WinAnsiEncoding' : 'StandardEncoding';
$differences = null;
if ($encoding instanceof PdfName) {
$base = $encoding->value;
} elseif ($encoding instanceof PdfDictionary) {
$named = self::name($doc->deref($encoding->get('BaseEncoding')));
$base = $named ?? $base;
$differences = $doc->deref($encoding->get('Differences'));
}
$this->encoding = SimpleEncodings::map($base);
if (is_array($differences)) {
$code = 0;
foreach ($differences as $item) {
$item = $doc->deref($item);
if (is_int($item)) {
$code = $item;
} elseif ($item instanceof PdfName) {
$text = GlyphNames::toUnicode($item->value);
if ($text !== null) {
$this->encoding[$code] = $text;
} else {
unset($this->encoding[$code]);
}
$code++;
}
}
}
}

private function simpleWidths(ReaderDocument $doc, PdfDictionary $font): void
{
$first = $doc->deref($font->get('FirstChar'));
$widths = $doc->deref($font->get('Widths'));
if (!is_int($first) || !is_array($widths)) {
return;
}
foreach (array_values($widths) as $i => $w) {
$w = $doc->deref($w);
if (is_int($w) || is_float($w)) {
$this->widths[$first + $i] = (float) $w;
}
}
}

/** /W: `c [w1 w2 …]` and `cFirst cLast w` entries; /DW the default. */
private function cidWidths(ReaderDocument $doc, PdfDictionary $cid): void
{
$dw = $doc->deref($cid->get('DW'));
if (is_int($dw) || is_float($dw)) {
$this->defaultWidth = (float) $dw;
}
$w = $doc->deref($cid->get('W'));
if (!is_array($w)) {
return;
}
$items = array_values(array_map(fn (mixed $v): mixed => $doc->deref($v), $w));
$count = count($items);
for ($i = 0; $i < $count;) {
$start = $items[$i];
$next = $items[$i + 1] ?? null;
if (is_int($start) && is_array($next)) {
foreach (array_values($next) as $k => $width) {
$width = $doc->deref($width);
if (is_int($width) || is_float($width)) {
$this->widths[$start + $k] = (float) $width;
}
}
$i += 2;
} elseif (is_int($start) && is_int($next) && isset($items[$i + 2]) && (is_int($items[$i + 2]) || is_float($items[$i + 2]))) {
if ($next - $start < 0x10000) {
for ($c = $start; $c <= $next; $c++) {
$this->widths[$c] = (float) $items[$i + 2];
}
}
$i += 3;
} else {
$i++;
}
}
}

private static function name(mixed $value): ?string
{
return $value instanceof PdfName ? $value->value : null;
}
}
Loading
Loading