Usage | pdf-to-text-go | Spatie       

 SPATIE  

pdf-to-text-go
==============

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Pdf-to-text-go](https://spatie.be/docs/pdf-to-text-go/v1)  Usage

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/pdf-to-text-go/v1) 

  Usage    
- [ Introduction ](https://spatie.be/docs/pdf-to-text-go/v1/introduction)
- [ Installation and setup ](https://spatie.be/docs/pdf-to-text-go/v1/installation-and-setup)
- [ Usage ](https://spatie.be/docs/pdf-to-text-go/v1/usage)
- [ Testing ](https://spatie.be/docs/pdf-to-text-go/v1/testing)
- [ Releasing ](https://spatie.be/docs/pdf-to-text-go/v1/releasing)
- [ Changelog ](https://spatie.be/docs/pdf-to-text-go/v1/changelog)
- [ Support us ](https://spatie.be/docs/pdf-to-text-go/v1/support-us)

 Usage
=====

###  On this page 

1. [ Extract text ](#content-extract-text)
2. [ Choose a binary ](#content-choose-a-binary)
3. [ Configure options and passwords ](#content-configure-options-and-passwords)
4. [ Timeouts and process customization ](#content-timeouts-and-process-customization)
5. [ Output and errors ](#content-output-and-errors)

Extract text
--------------------------------------------------------------------------------------------

Extracting text from a PDF is easy:

```
converter := pdftotext.New()
text, err := converter.Text(ctx, "book.pdf")
```

Or easier:

```
text, err := pdftotext.GetText(ctx, "book.pdf")
```

Examples use `pdftotext "github.com/spatie/pdf-to-text-go"`. Pass a `context.Context` as `ctx`, for example `context.Background()` in a command or the request context in a server. Always check the returned error before using the text.

Choose a binary
-----------------------------------------------------------------------------------------------------

By default the package searches common Linux, Homebrew, MacPorts and Windows Xpdf installation locations, then PATH. This adds PATH discovery to the PHP package's common-location search.

If the binary is located elsewhere, set its path:

```
converter := pdftotext.New()
converter.Binary = "/custom/path/to/pdftotext"
text, err := converter.Text(ctx, "book.pdf")
```

The binary can also be a command name such as `pdftotext`. Paths containing spaces work without shell quotes. Explicit binary paths are checked when the command runs. Automatic discovery also happens at extraction time, not construction time.

Configure options and passwords
-----------------------------------------------------------------------------------------------------------------------------------------------------

Sometimes you may want to use [pdftotext options](https://linux.die.net/man/1/pdftotext). To do so, use `SetOptions`:

```
text, err := pdftotext.New().
    SetOptions("layout", "r 96").
    Text(ctx, "table.pdf")
```

A leading hyphen is optional. Each option is trimmed like PHP's `trim` and split at its first ASCII space only. The remaining value is one argument, even when it contains spaces, quotes or shell metacharacters. Do not add shell quotes around values. Options go directly to the installed binary, so do not accept untrusted options.

For a password-protected PDF:

```
text, err := pdftotext.New().
    SetOptions("opw myP1$$Word").
    Text(ctx, "book.pdf")
```

Use `upw` for a user password. Passwords are native process arguments and may be visible through operating-system process inspection. The package's error messages do not add the command line. A custom binary's stderr and command hooks can still expose sensitive values. Do not log converter settings or native commands containing passwords.

Successive calls to `SetOptions` overwrite options passed in during previous calls.

If you need to make multiple calls to add options, for example to pass default options when creating the converter and context-specific options elsewhere, use `AddOptions`:

```
converter := pdftotext.New().SetOptions("layout", "r 96")
converter.AddOptions("f 1", "l 1")
text, err := converter.Text(ctx, "table.pdf")
```

Timeouts and process customization
--------------------------------------------------------------------------------------------------------------------------------------------------------------

`New` defaults to a 60-second timeout. Set `Timeout` to zero to disable it. Negative timeouts return an error. A zero-value `Converter` also works, with no timeout. Context cancellation and deadlines apply even when `Timeout` is zero.

The PHP process callback maps to `Configure`, which receives the native `exec.Cmd` before execution:

```
converter := pdftotext.New()
converter.Timeout = 120 * time.Second
converter.Configure = func(cmd *exec.Cmd) error {
    cmd.Dir = "/working/directory"
    cmd.Env = append(cmd.Environ(), "LC_ALL=C")
    return nil
}
text, err := converter.Text(ctx, "book.pdf")
```

Import `os/exec` and `time` for this example. The input is checked as a readable regular file and made absolute before the callback runs, so a working-directory change does not break relative input paths. Filenames beginning with a hyphen cannot become options. No shell is used.

The hook may change command settings or return an error to abort. Do not start the command in the hook. Keep its context cancellation fields when customizing it. After the hook, the package captures stdout and stderr and closes stdin. The timeout kills and waits for the direct child, not any descendants a custom binary starts. Output pipe waits are bounded to one second after cancellation or process exit through Go's `exec.Cmd.WaitDelay`, unless the hook changes it.

Converters can be reused for different input files. Concurrent calls to `Text` are safe if the hook is concurrency-safe and no configuration is changed during extraction.

Output and errors
-----------------------------------------------------------------------------------------------------------

`Text` returns a Go string and an error. It trims only space, tab, LF, CR, NUL, vertical tab and form feed from the edges. Unicode whitespace, interior page breaks and line endings remain unchanged. Go strings preserve arbitrary bytes, so options such as `enc Latin1` do not require a separate byte API. Use `[]byte(text)` if needed. Supported options and extraction output depend on the installed Poppler or Xpdf version.

Use `errors.Is` to check `pdftotext.ErrBinaryNotFound` for failed automatic discovery and `pdftotext.ErrPDFNotFound` for unreadable or non-file input. Underlying filesystem errors remain available through wrapping. A missing explicitly configured binary is a process-start failure instead.

Process failures return `*pdftotext.ExtractionError`. Its `Stderr` contains the converter's diagnostics and `Unwrap` exposes the cause. Use `errors.As` with `*exec.ExitError` to inspect an unsuccessful exit code. Cancellation and timeouts match `context.Canceled` and `context.DeadlineExceeded` through `errors.Is`. Hook errors are wrapped without losing their cause.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
