# Converting PDF to Markdown with OCR

**URL:** <https://community.openai.com/t/converting-pdf-to-markdown-with-ocr/762476>\
**Category:** API\
**Created:** [May 18, 2024, 10:31am UTC](https://community.openai.com/t/converting-pdf-to-markdown-with-ocr/762476 "2024-05-18T10:31:28Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![jochenschultz](https://sea2.discourse-cdn.com/openai1/user_avatar/community.openai.com/jochenschultz/32/491030_2.png) [@jochenschultz](https://community.openai.com/u/jochenschultz)\
**Post date:** [May 19, 2024, 1:17am UTC](https://community.openai.com/t/converting-pdf-to-markdown-with-ocr/762476/3 "2024-05-19T01:17:58Z")

</div>

> [@russell4](#):
>
> ChatGPT can convert PDF documents to Markdown, and does it extremely well. How can we access this functionality from the API?

Or maybe before you do that you can try without GPT-4?

Like this:

```python

import os
import base64
import pytesseract
from pdf2image import convert_from_path
from bs4 import BeautifulSoup

# Function to convert PDF to images
def pdf_to_images(pdf_path):
    return convert_from_path(pdf_path, fmt='tiff')

# Function to convert image to hOCR using pytesseract
def image_to_hocr(image):
    return pytesseract.image_to_pdf_or_hocr(image, extension='hocr')

# Function to convert hOCR to markdown
def hocr_to_markdown(hocr):
    soup = BeautifulSoup(hocr, 'html.parser')
    markdown_text = ""

    for line in soup.find_all('span', class_='ocr_line'):
        line_text = " ".join([word.get_text() for word in line.find_all('span', class_='ocrx_word')])
        markdown_text += f"{line_text}\n"

    return markdown_text

# Main function to convert PDF to Markdown
def pdf_to_markdown(pdf_path):
    images = pdf_to_images(pdf_path)
    markdown_text = ""

    for image in images:
        hocr = image_to_hocr(image)
        markdown_text += hocr_to_markdown(hocr) + "\n\n"

    return markdown_text

# Example usage
if __name__ == " __main__":
    pdf_path = "sample.pdf" # Path to your PDF file
    markdown_output = pdf_to_markdown(pdf_path)
    with open("output.md", "w") as file:
        file.write(markdown_output)

```

And then use GPT 4 only for semantical extraction?

Or maybe you can try something like this on your linux cli:

```shell
for img in $(pdfimages -tiff sample.pdf output); do tesseract "$img" stdout hocr | sed -n 's/.*ocr_line.*>\(.*\)<.*/\1/p' >> output.md; done

```

---

_[View the full topic](https://community.openai.com/t/converting-pdf-to-markdown-with-ocr/762476)._
