PdfParser (smalot/pdfparser)
| Language | PHP 7.1+ |
|---|---|
| License | LGPL-3.0 |
| Repository | github.com/smalot/pdfparser |
| Documentation | docs in the repository |
| Depends on | ext-zlib, ext-iconv, symfony/polyfill-mbstring |
| Read / write | yes / 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#
composer require smalot/pdfparser
Basic usage: extract text from a PDF#
<?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#
foreach ($pdf->getPages() as $i => $page) {
echo "--- page ", $i + 1, " ---\n";
echo $page->getText(), "\n";
}
How to read PDF metadata#
$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):
$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#
$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#
- Encrypted files throw an exception (“Secured pdf file are currently not supported”); decrypt them first with qpdf (
qpdf --decrypt) if you have the password. $pdf->getObjectsByType('XObject', 'Image')lists embedded images.- Wrap parsing of uploaded files in
try/catch: malformed PDFs throw exceptions.