Skip to chapter content
navan✳THE BUILD LABPYTHON / GUIDE
0/26 read
CHAPTER 17 / 26 · DOCUMENTS AND SERVICES

PDF and Word documents.

Recognise what each document format stores before extracting or generating text.

BY NAVAN SAMI5 MIN READTHEORY FIRST
01 / THE BASICS

Start here.

A PDF is primarily a page layout format. Words may be stored as selectable text or only as pixels in a scanned page, and reading order can be ambiguous in complex layouts. A Word .docx document stores paragraphs, runs, tables, and other structured parts. Python libraries expose these structures, but the result is not always one plain string in the order a human sees on screen.

A PDF parser can extract text from a text-based PDF, while an image-only scan may need OCR. A Word library such as python-docx can visit paragraphs and tables or create a new document. A paragraph is a block of text; a run is a segment within it that can carry formatting. Editing a document requires understanding which structure owns the words you want to change.

The safe pattern is to read from a source file and write a new output file. Check page count, extracted text, and formatting assumptions before treating the result as complete. A generated document can be syntactically valid but visually poor, especially with tables or page breaks. Keep the difference between the data you intend to communicate and the layout that a reader will actually see.

02 / THE IDEA

Build the model.

A PDF is designed around pages and positioned content, while a Word document is structured around paragraphs, runs, styles, tables, and sections. They may look similar on screen, but their data models are different. Before automating either one, decide whether you need text extraction, content generation, page reordering, or exact visual fidelity.

A PDF may contain real text, images of text, or both. A library can extract embedded text, but a scanned page needs optical character recognition. Extracted PDF text may have surprising reading order because the file stores drawing instructions, not necessarily a simple stream of sentences. Validate the result before using it as authoritative data.

03 / UNDER THE SURFACE

How it works.

pypdf can read pages, extract text where it exists, and write selected pages to a new file. Keep page order explicit and handle None when a page has no extractable text. Avoid overwriting the source while testing a transformation. For sensitive files, remember that extracted text and temporary output may contain private information.

python-docx works with Word .docx files. A paragraph may contain multiple runs with different formatting; joining paragraph.text is convenient for reading but does not preserve every style boundary. When generating a document, use headings and paragraph styles instead of manually adding spaces or repeated blank lines. A saved .docx is a new artifact, not a live connection to Word.

A combined workflow often looks like this: extract or read structured content, turn it into your own validated record model, then generate an output document. Keeping the middle model independent of PDF or Word makes the transformation testable and prevents a layout quirk from becoming a business rule.

04 / A WORKED EXAMPLE

Read it line by line.

example.py
from docx import Document
report = Document()
report.add_heading('Weekly report', level=1)
report.add_paragraph('Three tasks completed.')
report.save('weekly-report.docx')

Document creates a blank Word document. add_heading gives the title a heading style, add_paragraph adds body text, and save writes a .docx file. The example depends on the optional python-docx package. A successful save confirms that the file was written, while its visible layout is a separate property of the generated document.

05 / ANOTHER EXAMPLE

See the rule again.

example-2.py
from docx import Document
report = Document('weekly-report.docx')
for paragraph in report.paragraphs:
    if paragraph.text.strip():
        print(paragraph.text)

This prints nonblank paragraphs in document order, including the heading and body text from the example. It reads paragraph text, not every possible table or header; expand the traversal if those parts matter.

06 / REMEMBER THIS

A mistake to avoid.

Do not assume a PDF parser can read text from a scanned image. OCR is a separate process with its own error rate, language settings, and need for human verification.

Finished this chapter?
Built with curiosity. By Navan Sami. ↗Python · Understand the idea, then write the code.