All formats

PdfParser (smalot/pdfparser)

LanguagePHP 7.1+
LicenseLGPL-3.0
Repositorygithub.com/smalot/pdfparser
Documentationdocs in the repository
Depends onext-zlib, ext-iconv, symfony/polyfill-mbstring
Read / writeyes / no

PdfParser parses PDF files in pure PHP, without external tools: it decodes streams and fonts (including ToUnicode maps and common encodings) and returns the text of the whole document or of each page, text with transformation matrices (positions), document metadata, and the raw objects. It’s the usual choice for indexing or searching PDF content in PHP applications.

It doesn’t open encrypted (“secured”) PDFs, doesn’t render, and isn’t meant for huge files: the whole document is parsed into memory. Text order follows the content stream, so multi-column layouts can come out interleaved; for better extraction call pdftotext (Poppler) if you can run external programs.

Installation#

Shell
composer require smalot/pdfparser

Basic usage: extract text from a PDF#

PHP
<?php
require 'vendor/autoload.php';

$parser = new \Smalot\PdfParser\Parser();
$pdf = $parser->parseFile('in.pdf');

echo $pdf->getText();

How to extract text page by page#

PHP
foreach ($pdf->getPages() as $i => $page) {
    echo "--- page ", $i + 1, " ---\n";
    echo $page->getText(), "\n";
}

How to read PDF metadata#

PHP
$details = $pdf->getDetails();  // Title, Author, Producer, CreationDate, Pages, ...
foreach ($details as $key => $value) {
    echo $key, ': ', is_array($value) ? implode(', ', $value) : $value, "\n";
}

How to get text with positions#

getDataTm() returns each text chunk with its text matrix; elements 4 and 5 are the x and y position in points (origin bottom-left):

PHP
$page = $pdf->getPages()[0];
foreach ($page->getDataTm() as [$matrix, $text]) {
    echo "{$text} at x={$matrix[4]} y={$matrix[5]}\n";
}

How to parse a PDF from memory and limit memory use#

PHP
$config = new \Smalot\PdfParser\Config();
$config->setRetainImageContent(false);              // don't keep image data in memory
$config->setDecodeMemoryLimit(64 * 1024 * 1024);    // cap decoded stream size

$parser = new \Smalot\PdfParser\Parser([], $config);
$pdf = $parser->parseContent($pdfBytes);            // e.g. from an upload or a database
echo count($pdf->getPages()), " pages\n";

Tips#