How to Extract PDF Text with Python
Why Extract PDF Text with Python?
The pdfRest Extract Text API Tool is designed to help users extract text from PDF documents programmatically. This tutorial will demonstrate how to use Python to send an API call to the Extract Text endpoint.
This functionality can be particularly useful in scenarios where text needs to be extracted for data analysis, content repurposing, or for feeding into other software systems for further processing.
Extract PDF Text Python Code Example
from requests_toolbelt import MultipartEncoder
import requests
import json
extract_text_endpoint_url = 'https://api.pdfrest.com/extracted-text'
# The /extracted-text endpoint can take a single PDF file or id as input.
#This sample demonstrates extracting the text from a document to return as JSON
mp_encoder_extractText = MultipartEncoder(
fields={
'file': ('file_name.pdf', open('/path/to/file', 'rb'), 'application/pdf'),
'word_style': 'on',
}
)
# Let's set the headers that the extracted-text endpoint expects.
# Since MultipartEncoder is used, the 'Content-Type' header gets set to 'multipart/form-data' via the content_type attribute below.
headers = {
'Accept': 'application/json',
'Content-Type': mp_encoder_extractText.content_type,
'Api-Key': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' # place your api key here
}
print("Sending POST request to extracted-text endpoint...")
response = requests.post(extract_text_endpoint_url, data=mp_encoder_extractText, headers=headers)
print("Response status code: " + str(response.status_code))
if response.ok:
response_json = response.json()
print(json.dumps(response_json, indent = 2))
else:
print(response.text)
Source: GitHub - datalogics/pdf-rest-api-samples
Breaking Down the Python Code
The script combines requests with MultipartEncoder from requests-toolbelt. Install both external packages with python -m pip install requests requests-toolbelt when they are not already available.
extract_text_endpoint_url = 'https://api.pdfrest.com/extracted-text'
The /extracted-text endpoint accepts an uploaded PDF or an existing resource ID. This example uses a multipart upload and returns extraction results directly as JSON.
mp_encoder_extractText = MultipartEncoder(
fields={
'file': ('file_name.pdf', open('/path/to/file', 'rb'), 'application/pdf'),
'word_style': 'on',
}
)
The file tuple supplies the multipart filename, binary stream, and media type. Setting word_style to on adds a word list containing font, size, color, and color-space information. It does not perform OCR; image-only PDFs should first be processed with the OCR PDF tool when their visible text must be extracted.
headers = {
'Accept': 'application/json',
'Content-Type': mp_encoder_extractText.content_type,
'Api-Key': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
}
The encoder’s content type includes the required multipart boundary. The API key authenticates the request, and Accept: application/json asks the service to return the extraction data in the response.
response = requests.post(
extract_text_endpoint_url,
data=mp_encoder_extractText,
headers=headers
)
Passing the encoder through data sends the file and options as one multipart body. Additional endpoint controls can select pages, preserve line breaks, include word coordinates, or save the result as a downloadable JSON resource.
if response.ok:
response_json = response.json()
print(json.dumps(response_json, indent=2))
else:
print(response.text)
The success path pretty-prints the returned text and metadata. The failure path preserves the API’s validation or processing message instead of trying to parse an error as a successful extraction result.
Beyond the Tutorial
In this tutorial, we've walked through how to make a multipart API call to the pdfRest Extract Text endpoint using Python. This allows for the extraction of text from a PDF document and can be used in various applications where text data is needed from PDF files.
For further exploration, you're encouraged to demo all of the pdfRest API Tools in the API Lab and refer to the API Reference documentation.
Note: This is an example of a multipart API call. Code samples using JSON payloads can be found at GitHub - datalogics/pdf-rest-api-samples.