# Python Script Help - Exporting PDF Text and Images to a Word Document

**URL:** <https://discuss.python.org/t/python-script-help-exporting-pdf-text-and-images-to-a-word-document/54960>\
**Category:** Python Help\
**Tags:** help\
**Created:** [June 4, 2024, 7:09pm UTC](https://discuss.python.org/t/python-script-help-exporting-pdf-text-and-images-to-a-word-document/54960 "2024-06-04T19:09:46Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![BrittNBI](https://avatars.discourse-cdn.com/v4/letter/b/bc79bd/32.png) [@BrittNBI](https://discuss.python.org/u/BrittNBI)\
**Post date:** [June 4, 2024, 7:09pm UTC](https://discuss.python.org/t/python-script-help-exporting-pdf-text-and-images-to-a-word-document/54960/1 "2024-06-04T19:09:46Z")

</div>

I need help modifying this code below. The purpose of the code is to export the paragraphs in this PDF that contain an asterisk along with the associated photos directly below the paragraphs. The issue I am running into, is that it is exporting ALL the images on the page with the paragraphs. I only need it to extract the images directly below the paragraphs with the asterisk.

import fitz # PyMuPDF  
from docx import Document  
from docx.shared import Inches  
import io  
from PIL import Image

# Load the PDF document

pdf\_document = fitz.open(“Sample Home.pdf”)

# Create a Word document

word\_document = Document()

# Iterate through each page of the PDF

for page\_num in range(pdf\_document.page\_count):  
page = pdf\_document.load\_page(page\_num)  
blocks = page.get\_text(“blocks”)

```
for block in blocks:
    block_text = block[4]

    # Check if the paragraph includes an asterisk
    if '*' in block_text:
        # Add the paragraph to the Word document
        word_document.add_paragraph(block_text)

        # Extract images associated with this paragraph
        image_list = page.get_images(full=True)
        for image_index, img in enumerate(image_list):
            xref = img[0]
            base_image = pdf_document.extract_image(xref)
            image_bytes = base_image["image"]

            # Load image using PIL
            image = Image.open(io.BytesIO(image_bytes))
            image_filename = f"image_{page_num}_{image_index}.png"
            image.save(image_filename)

            # Add image to the Word document
            word_document.add_picture(image_filename, width=Inches(5))

```

# Save the Word document

word\_document.save(“Extracted\_Paragraphs\_and\_Images.docx”)
