- Как с помощью PHP можно распарсить PDF?
- Извлечение текста из PDF файла в PHP
- Комментарии ( 0 ):
- Saved searches
- Use saved searches to filter your results more quickly
- License
- smalot/pdfparser
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- How to Parse PDF in PHP
- Setup
- Generate PDF File
- Extract PDF Metadata
- Extract Text
- Closing
- About the author
- John Otieno
Как с помощью PHP можно распарсить PDF?
Задача: открыть документ и получить удобоваримый текст.
Опробовано: всё. Действительно всё, у меня весь гугл в сиреневых ссылках и даже контекстная реклама меня уже жалеет и предлагает купить ридер пдф книг.
Помимо PHP готов использовать любую другую технологию которая даст гарантированный результат. Но все же не хотелось бы уходить от родного для проекта языка.
Хардкорный вариант с написанием парсера с нуля по спекам формата не особо желателен в силу запутанности формата и зоопарка версий.
Оценить 1 комментарий
Варианты:
1. pdftotext -> plainttext
2. pdftohtml -> html, xml
3. habrahabr.ru/post/130601/ — конвертирование в .svg (визуально круто, в коде пока все еще слабо)
Пока нет ничего что бы работало 🙁
Как вы себе представляете такое преобразование, если в PDF текст хранится строками с определенными координатами, а не абзацами, например? Также текст может храниться картинкой или векторным форматом. Таблицы хранятся набором кусков текста и линиями. Заголовок — просто строка текста чуть большего размера.
Чтобы восстановить логическую структуру текста, надо систему вроде той, которая используется в продуктах fineReader. Систем эта сложная и на ее разработку у Abbee ушла куча денег, вряд ли вы сможете решить задачу проще. А без этого максимум, что вы можете вытащить из файла — это набор блоков вида «строчка такого-то текста расположена по таким-то координатам». Текст может быть разбит переносами.
Абзацы, конечно, еще можно из этого как-то восстановить, выстроив строчки по возрастанию координат, но переносы останутся, а любые нестандартные вещи, вроде подписи к картинке, будут ломать этот алгоритм.
Резюмируя, выберите другой исходный формат, или откажитесь от мысли преобразовать PDF в осмысленный текст, преобразуйте его в картинку например. Иначе вы всю жизнь будете дописывать костыли, как только кто-то захочет подснуть вашей системе текст, сверстанный другим способом.
Я прекрасно представляю себе формат и информация в нашем случае не храниться картинкой или вектором. Я представляю сложность данной задачи, но что поделать задача есть и её надо решать.
Извлечение текста из PDF файла в PHP
Порой бывает необходимо извлечь текст из PDF файла средствами PHP и далее я Вам покажу пример скрипта, который решаете данную проблему.
Устанавливаем необходимую библиотеку:
composer require smalot/pdfparser
// подключаем загрузчик
include ‘vendor/autoload.php’;
// Создаем объект для парсинга PDF
$parser = new \Smalot\PdfParser\Parser();
// парсим PDF файл
$pdf = $parser->parseFile(‘technic_report.pdf’);
// выводим текст из файла
print $pdf -> getText();
Обратите внимание на то, что текст, который Вы получите из pdf файла не будет иметь исходного форматирования документа. Однако это не так уж и важно, чтобы извлечь из текста интересующие Вас данные.
Если в PDF файле несколько страниц, то можно пройтись по каждой странице по отдельности:
// ссылка из PDF
// Извлекаем все страницы из PDF файла
$pages = $pdf->getPages();
// проходимся по каждой странице и получаем текст
foreach ($pages as $page) echo $page->getText();
>
А здесь можно получить метаданные PDF файла:
// извлекаем метаданные из pdf файла
$details = $pdf -> getDetails();
// Проходимся по каждому значению.
foreach ($details as $property => $value) if (is_array($value)) $value = implode(‘, ‘, $value);
>
echo $property . ‘ => ‘ . $value . «\n»;
>
Вот так просто можно, например, автоматизировать обработку большого количества PDF файлов в PHP, извлекая из них необходимые данные.
Создано 14.05.2019 08:56:04
Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!
Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.
Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления
Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.
Порекомендуйте эту статью друзьям:
Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):
- Кнопка:
Она выглядит вот так: - Текстовая ссылка:
Она выглядит вот так: Как создать свой сайт - BB-код ссылки для форумов (например, можете поставить её в подписи):
Комментарии ( 0 ):
Для добавления комментариев надо войти в систему.
Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.
Copyright © 2010-2023 Русаков Михаил Юрьевич. Все права защищены.
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
PdfParser, a standalone PHP library, provides various tools to extract data from a PDF file.
License
smalot/pdfparser
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
* Update Element.php Add ability for PdfParser to parse metadata names with hexadecimal encoded characters such as «Document#20Type» where \#20 is a space. Resolves Issue #529 * Update ElementTest.php Add test for spaces in metadata property names. * Make sure we fully support hex Too quick on the commit! Make sure our two ‘digit’ regexp also finds A-F hex digits. Add a test for #2d which is a hyphen. * fixed coding style issue in Element.php ——— Co-authored-by: Konrad Abicht
Git stats
Files
Failed to load latest commit information.
README.md
The smalot/pdfparser is a standalone PHP package that provides various tools to extract data from PDF files.
This library is under active maintenance. There is no active development by the author of this library (at the moment), but we welcome any pull request adding/extending functionality!
- Load/parse objects and headers
- Extract metadata (author, description, . )
- Extract text from ordered pages
- Support of compressed PDFs
- Support of MAC OS Roman charset encoding
- Handling of hexa and octal encoding in text sections
- Create custom configurations (see CustomConfig.md).
Currently, secured documents and extracting form data are not supported.
This library is under the LGPLv3 license.
This library requires PHP 7.1+ since v1. You can install it via Composer:
composer require smalot/pdfparser
In case you can’t use Composer, you can include alt_autoload.php-dist . It will include all required files automatically.
// Parse PDF file and build necessary objects. $parser = new \Smalot\PdfParser\Parser(); $pdf = $parser->parseFile('/path/to/document.pdf'); $text = $pdf->getText(); echo $text;
Further usage information can be found here.
Documentation can be found in the doc folder.
About
PdfParser, a standalone PHP library, provides various tools to extract data from a PDF file.
How to Parse PDF in PHP
Have you ever tried to open a PDF file to search for a specific line or word? It does not work. All you will find is binary data that makes absolutely no sense.
Parsing PDF files is very tedious and complicated for any software developer, not because it’s complex but because of the nature of PDF files. PDF files contain objects which are identified by a unique number. PDF objects can collect information such as images, text, and more. These objects are encrypted and compressed, making it nearly impossible to process PDFs as text documents.
This guide will learn how to parse PDF documents using the PHP programming language.
Setup
The first step is to set up a development environment. We will start by installing PHP and the required libraries.
To install PHP, open the terminal and enter the command:
Once PHP is installed, use it to install Composer as shown in the commands:
php — r «copy(‘https://getcomposer.org/installer’, ‘composer-setup.php’);»
php — r «if (hash_file(‘sha384’, ‘composer-setup.php’) ===
unlink(‘composer-setup.php’); > echo PHP_EOL;»
php — r «unlink(‘composer-setup.php’);»
Once we have the composer installed and set up, we can proceed to use the PDFParser library.
Open the terminal and enter the command:
Generate PDF File
The next step is to select a PDF file for use. There are various ways and resources you can use to create a PDF file. For example, if you are on Windows, you can export a .doc/docx document to pdf.
However, for this example, we will use free files readily available on the internet. Open your browser and navigate to the resource provided below:
Please select one of the available PDF files and save it on your system.
NOTE: Ensure to check for malicious files before using such documents. Tools such as VirusTotal are great resources.
The following is a scan report of sample1.pdf file.
Extract PDF Metadata
To extract metadata from the PDF using the PDF parser library, we can implement sample code as shown below:
// include composer autoloader
$parser = new \Smalot\PdfParser\Parser ( ) ;
$pdf = $parser -> parseFile ( «sample1.pdf» ) ;
$metadata = $pdf — getDetails ( ) ;
foreach ( $metadata as meta => $value ) {
The above code should fetch metadata information about the file. Such information includes:
CreationDate : 2016 — 12 — 22T11 : 43 : 55 — 05 : 00
Creator : Adobe InDesign CC 2015 ( Macintosh )
ModDate : 2016 — 12 — 29T15 : 47 : 20 — 05 : 00
Producer : Adobe PDF Library 15.0
Extract Text
To extract text from each page of the submitted PDF, we can implement the code as shown below:
$parser = new \Smalot\PdfParser\Parser ( ) ;
$pdf = $parser -> parseFile ( «sample1.pdf» ) ;
Once we run the code above, we should see the text extracted from the sample1.pdf file. Example ouput is as shown below:
Closing
This guide shows you how you can parse PDF files using PHP and the PDFParser library. Check the documentation to learn more.
About the author
John Otieno
My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list