title: How to convert PDF to clean HTML using Python
body: <p>I want to have the user upload a PDF, convert that PDF to HTML code and insert this code into a <code>&lt;div&gt;</code> to display the PDF document. I'm using PDFMiner to analyze the uploaded PDF. When I convert it to HTML, the HTML is messy and the document is wrongly displayed <a href="https://i.stack.imgur.com/An3mr.png" rel="nofollow noreferrer">HTML Mess</a>
  . I've tried XML, but it's still unusable because the text gets displayed with no spaces. How can I improve this? Thank you.</p>
  
  <pre><code>
  def main():
  
   contentRaw =  convert_pdf(file.filename, 'html')
   contentR = json.dumps(contentRaw)
   contentOut = (contentRaw)
   return render_template('app.html', title=" App", filename=file.filename, content=Markup(contentOut), instructions=instructions)
  
  
  
  def convert_pdf(path, format='text', codec='utf-8', password=''):
      rsrcmgr = PDFResourceManager()
      retstr = BytesIO()
      laparams = LAParams()
      if format == 'text':
          device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
      elif format == 'html':
          device = HTMLConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
      elif format == 'xml':
          device = XMLConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
      else:
          raise ValueError('provide format, either text, html or xml!')
      fp = open(path, 'rb')
      interpreter = PDFPageInterpreter(rsrcmgr, device)
      maxpages = 0
      caching = True
      pagenos=set()
      for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True):
          interpreter.process_page(page)
  
      text = retstr.getvalue().decode()
      fp.close()
      device.close()
      retstr.close()
      return text
  
  </code></pre>