spatie/pdf-to-text

repository·main·Indexed 21 days ago

https://github.com/spatie/pdf-to-text

A PHP package that provides a simple interface to extract text from PDF files by leveraging the pdftotext command-line tool. It features a fluent API via the Pdf class, support for custom binary paths, and the ability to configure pdftotext options. Requires the pdftotext binary (part of poppler-utils) to be installed on the system.

Tokens
1.6K
Snippets
9
Records
9
Agent score
75%

What's inside spatie/pdf-to-text

  1. Install the required pdftotext binary

    main

    This package requires the pdftotext binary (part of poppler-utils) to be installed on your system. Use the command corresponding to your operating system:

    • Ubuntu/Debian: apt-get install poppler-utils
    • macOS: brew install poppler
    • RedHat/CentOS/Rocky Linux/Fedora: yum install poppler-utils
    • Windows: Download Xpdf command line tools and ensure the path to pdftotext.exe is accessible (e.g., C:\Program Files\xpdf-tools-win\bin64\pdftotext.exe).

    You can verify the installation by running which pdftotext in your terminal.

    which pdftotext
  2. Extract text from a PDF using the Pdf class

    main

    You can extract text using either a static method for simplicity or an instance-based approach for more control.

    use Spatie\PdfToText\Pdf;
    
    // Simple static approach
    echo Pdf::getText('book.pdf');
    
    // Instance-based approach
    $text = (new Pdf())
        ->setPdf('book.pdf')
        ->text();
  3. Specify a custom path to the pdftotext binary

    main

    By default, the package assumes pdftotext is located at /usr/bin/pdftotext. If your binary is located elsewhere, you must provide the path to the constructor or as a parameter to the static method.

    // Via constructor
    $text = (new Pdf('/custom/path/to/pdftotext'))
        ->setPdf('book.pdf')
        ->text();
    
    // Via static method
    echo Pdf::getText('book.pdf', '/custom/path/to/pdftotext');
  4. Configure pdftotext options

    main

    You can pass specific pdftotext options to the underlying binary using setOptions() or addOptions().

    • setOptions(array $options): Overwrites any previously set options.
    • addOptions(array $options): Appends options to the existing set.

    Note: Successive calls to setOptions() will overwrite previous options.

    // Using setOptions on an instance
    $text = (new Pdf())
        ->setPdf('table.pdf')
        ->setOptions(['layout', 'r 96'])
        ->text();
    
    // Using addOptions to append to existing options
    $text = (new Pdf())
        ->setPdf('table.pdf')
        ->setOptions(['layout', 'r 96'])
        ->addOptions(['f 1'])
        ->text();
    
    // Using the static method with options as the third parameter
    echo Pdf::getText('book.pdf', null, ['layout', 'opw myP1$$Word']);
  5. Extract text from a PDF using the Pdf class

    main

    The Spatie\PdfToText\Pdf class is the primary interface for extracting text from PDF files using the pdftotext binary.

    Basic Usage

    You can use the static getText() method for a quick, one-off extraction:

    use Spatie\PdfToText\Pdf;
    
    $text = Pdf::getText('path/to/document.pdf');

    Fluent API

    For more complex configurations, you can instantiate the class and use its fluent interface:

    1. Initialize: Pass a custom $binPath to the constructor if the binary is not in a standard location.
    2. Set PDF: Use setPdf(string $pdf) to specify the file.
    3. Configure Options: Use setOptions(array $options) to replace existing options or addOptions(array $options) to append them.
    4. Set Timeout: Use setTimeout(int $timeout) to define the maximum execution time in seconds.
    5. Execute: Call text() to perform the extraction.
    use Spatie\PdfToText\Pdf;
    
    $text = Pdf::make()
        ->setPdf('path/to/document.pdf')
        ->setOptions(['-layout']) // Example option
        ->setTimeout(120)
        ->text();
    use Spatie\PdfToText\Pdf;
    
    $text = Pdf::getText('path/to/document.pdf');
  6. Extend the extraction process with a callback

    main

    The text() method and the getText() static method accept an optional ?Closure $callback. This callback receives the underlying Symfony\Component\Process\Process instance, allowing you to modify the process behavior before it runs.

    This is useful for advanced process manipulation or debugging.

    use Spatie\PdfToText\Pdf;
    use Symfony\Component\Process\Process;
    
    $text = Pdf::getText('document.pdf', null, [], 60, function (Process $process) {
        // You can modify the process here
        return $process;
    });
    $text = Pdf::getText('document.pdf', null, [], 60, function (Process $process) {
        return $process;
    });
  7. Customize the pdftotext binary path

    main

    By default, the Pdf class attempts to locate the pdftotext binary in several common system paths (e.g., /usr/bin/pdftotext, /opt/homebrew/bin/pdftotext, or Windows paths).

    If the binary is in a non-standard location, you must provide the absolute path to the binary when instantiating the class or via the getText() static method.

    use Spatie\PdfToText\Pdf;
    
    // Via constructor
    $pdf = new Pdf('/custom/path/to/pdftotext');
    
    // Via static method
    $text = Pdf::getText('document.pdf', '/custom/path/to/pdftotext');

    If the binary cannot be found or is not executable, a Spatie\PdfToText\Exceptions\BinaryNotFoundException will be thrown.

    $pdf = new Pdf('/custom/path/to/pdftotext');
  8. Handle text extraction failures with CouldNotExtractText

    main

    When the underlying process used to extract text from a PDF fails, the library throws a Spatie\PdfToText\Exceptions\CouldNotExtractText exception. This exception extends Symfony's ProcessFailedException, meaning it carries information about the failed process that can be used for debugging.

    use Spatie\PdfToText\Exceptions\CouldNotExtractText;
    
    try {
        // Code that calls the PDF to text extraction
    } catch (CouldNotExtractText $exception) {
        // Handle the failure
    }