To extract document titles, subtitles, sections, and subsections from a PDF using the pdfminer library in Python, you can leverage the library's ability to read and analyze the structure of a PDF. Below is a sample code snippet that demonstrates how to extract headings based on their font size or specific text patterns. Note that this example assumes that the titles, subtitles, and sections are distinguishable by their font sizes or line characteristics.
Make sure you have pdfminer.six installed. You can install it using pip if you haven't done so:
pip install pdfminer.six
Here’s a basic example of how to extract headings up to 5 levels deep:
from pdfminer.high_level import extract_text
from pdfminer.layout import LAParams, LTTextBoxHorizontal, LTChar
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.converter import TextConverter
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.layout import LTPage, LTTextBox, LTTextLine
import io
class PDFHeadingExtractor:
def __init__(self, pdf_path):
self.pdf_path = pdf_path
self.headings = []
def extract_headings(self):
with open(self.pdf_path, 'rb') as fh:
for page_layout in self.extract_layout(fh):
self.process_page(page_layout)
return self.headings
def extract_layout(self, fh):
"""Extract the layout of pages."""
rsrcmgr = PDFResourceManager()
laparams = LAParams()
device = TextConverter(rsrcmgr, io.StringIO(), laparams=laparams)
interpreter = PDFPageInterpreter(rsrcmgr, device)
from pdfminer.pdfpage import PDFPage
for page in PDFPage.get_pages(fh):
interpreter.process_page(page)
yield device.get_result() # Returns LTPage
device.close()
def process_page(self, page_layout):
"""Process each page layout to extract headings."""
for element in page_layout:
if isinstance(element, LTTextBoxHorizontal):
self.extract_headings_from_textbox(element)
def extract_headings_from_textbox(self, textbox):
"""Extract headings from a text box based on font size."""
for text_line in textbox:
if isinstance(text_line, LTTextLine):
for character in text_line:
if isinstance(character, LTChar):
# You can define font size thresholds for each level
font_size = character.size
if font_size > 18: # This threshold can vary
level = 1 # Title
elif 14 < font_size <= 18:
level = 2 # Subtitle
elif 12 < font_size <= 14:
level = 3 # Section
elif 10 < font_size <= 12:
level = 4 # Subsection
else:
level = 5 # Further Subsections
# Collect heading if it's a heading
heading_text = text_line.get_text().strip()
if heading_text:
self.headings.append({
'level': level,
'text': heading_text
})
# Usage
pdf_path = 'your_document.pdf' # Replace with your PDF file path
extractor = PDFHeadingExtractor(pdf_path)
headings = extractor.extract_headings()
# Print the extracted headings
for heading in headings:
print("Level {}: {}".format(heading['level'], heading['text']))
Note:
- Font Size Thresholds: The thresholds for font sizes are arbitrary in this example. You may need to adjust these values according to your PDF document's formatting.
- Heading Patterns: Depending on the document, headings may not always correspond to font sizes. More advanced logic may be required for consistency across various documents.
- Output: The script prints the headings along with their levels.
Before running the code, ensure that your PDF is structured in a way that allows pdfminer to detect the headings correctly. If your document has a different structure, you may need to modify the logic accordingly.