title: Extracting text from scanned PDF without saving the scan as a new file image
body: <p>I would like to extract text from scanned PDFs.<br />
  My &quot;test&quot; code is as follows:</p>
  <pre><code>from pdf2image import convert_from_path
  from pytesseract import image_to_string
  from PIL import Image
  
  converted_scan = convert_from_path('test.pdf', 500)
  
  for i in converted_scan:
      i.save('scan_image.png', 'png')
      
  text = image_to_string(Image.open('scan_image.png'))
  with open('scan_text_output.txt', 'w') as outfile:
      outfile.write(text.replace('\n\n', '\n'))
  </code></pre>
  <p>I would like to know if there is a way to extract the content of the image directly from the object <code>converted_scan</code>, without saving the scan as a new &quot;physical&quot; image file on the disk?</p>
  <p>Basically, I would like to skip this part:</p>
  <pre><code>for i in converted_scan:
      i.save('scan_image.png', 'png')
  </code></pre>
  <p>I have a few thousands scans to extract text from. Although all the generated new image files are not particularly heavy, it's not negligible and I find it a bit overkill.</p>
  <p><strong>EDIT</strong></p>
  <p>Here's a slightly different, more compact approach than Colonder's answer, based on <a href="https://pythontips.com/2016/02/25/ocr-on-pdf-files-using-python/" rel="nofollow noreferrer">this post</a>. For .pdf files with many pages, it might be worth adding a progress bar to each loop using e.g. the <code>tqdm</code> module.</p>
  <pre><code>from wand.image import Image as w_img
  from PIL import Image as p_img
  import pyocr.builders
  import regex, pyocr, io
  
  infile = 'my_file.pdf'
  tool = pyocr.get_available_tools()[0]
  tool = tools[0]
  req_image = []
  txt = ''
  
  # to convert pdf to img and extract text
  with w_img(filename = infile, resolution = 200) as scan:
      image_png = scan.convert('png')
      for i in image_png.sequence:
          img_page = w_img(image = i)
          req_image.append(img_page.make_blob('png'))
      for i in req_image:
          content = tool.image_to_string(
              p_img.open(io.BytesIO(i)),
              lang = tool.get_available_languages()[0],
              builder = pyocr.builders.TextBuilder()
          )
          txt += content
  
  # to save the output as a .txt file
  with open(infile[:-4] + '.txt', 'w') as outfile:
      full_txt = regex.sub(r'\n+', '\n', txt)
      outfile.write(full_txt)
  </code></pre>