title: How to solve "AttributeError: 'QPDFDocument' object has no attribute 'initialize' " in python
body: <p>I have got the following error when I'm trying to execute example in pdfquery.
    File "C:\workspace-php\test\pdfminer\pdfqueries\pdfquery.py", line 187, in <strong>init</strong>
      doc.initialize()
  AttributeError: 'QPDFDocument' object has no attribute 'initialize'</p>
  
  <p>I'm trying to solve this but still i dont get any solution for that.it would be appreciated if some one can help me to solve this.</p>
  
  <pre><code>class PDFQuery(object):
      def __init__(self, file,
                      merge_tags=('LTChar', 'LTAnno'),
                      round_floats=True,
                      round_digits=3,
                      input_text_formatter=None,
                      normalize_spaces=True,
                      resort=True,
                      parse_tree_cacher=None,
                      ):
          # store input
          self.merge_tags = merge_tags
          self.round_floats = round_floats
          self.round_digits = round_digits
          self.resort = resort
  
          # set up input text formatting function, if any
          if input_text_formatter:
              self.input_text_formatter = input_text_formatter
          elif normalize_spaces:
              r = re.compile(r'\s+')
              self.input_text_formatter = lambda s: re.sub(r, ' ', s)
          else:
              self.input_text_formatter = None
  
          # open doc
          if not hasattr(file, 'read'):
              try:
                  file = open(file, 'rb')
              except TypeError:
                  raise TypeError("File must be file object or filepath string.")
  
          parser = PDFParser(file)
          if hasattr(QPDFDocument, 'set_parser'):
              # pdfminer &lt; 20131022
              doc = QPDFDocument()
              parser.set_document(doc)
              doc.set_parser(parser)
          else:
              # pdfminer &gt;= 20131022
              doc = QPDFDocument(parser)
              parser.set_document(doc)
          doc.initialize()
          self.doc = doc
          self.parser = parser
          self.tree = None
          self.pq = None
          self.file = file
  
          if parse_tree_cacher:
              self._parse_tree_cacher = parse_tree_cacher
              self._parse_tree_cacher.set_hash_key(self.file)
          else:
              self._parse_tree_cacher = DummyCache()
  
          # set up layout parsing
          rsrcmgr = PDFResourceManager()
          laparams = LAParams(all_texts=True, detect_vertical=True)
          self.device = PDFPageAggregator(rsrcmgr, laparams=laparams)
          self.interpreter = PDFPageInterpreter(rsrcmgr, self.device)
  
          # caches
          self._pages = []
          self._pages_iter = None
          self._elements = []
  
      def load(self, *page_numbers):
          """
              Load etree and pyquery object for entire document, or given page numbers (ints or lists).
              After this is called, objects are available at pdf.tree and pdf.pq.
  
              &gt;&gt;&gt; pdf.load()
              &gt;&gt;&gt; pdf.tree
              &lt;lxml.etree._ElementTree object at ...&gt;
              &gt;&gt;&gt; pdf.pq('LTPage')
              [&lt;LTPage&gt;, &lt;LTPage&gt;]
              &gt;&gt;&gt; pdf.load(1)
              &gt;&gt;&gt; pdf.pq('LTPage')
              [&lt;LTPage&gt;]
              &gt;&gt;&gt; pdf.load(0,1)
              &gt;&gt;&gt; pdf.pq('LTPage')
              [&lt;LTPage&gt;, &lt;LTPage&gt;]
          """
          self.tree = self.get_tree(*_flatten(page_numbers))
          self.pq = self.get_pyquery(self.tree)
  
      def extract(self, searches, tree=None, as_dict=True):
          """
              &gt;&gt;&gt; foo = pdf.extract( [ ['pages', 'LTPage'] ])
              &gt;&gt;&gt; foo
              {'pages': [&lt;LTPage&gt;, &lt;LTPage&gt;]}
              &gt;&gt;&gt; pdf.extract( [ ['bar', ':in_bbox("100,100,400,400")'] ], foo['pages'][0])
              {'bar': [&lt;LTTextLineHorizontal&gt;, &lt;LTTextBoxHorizontal&gt;,...
          """
          if self.tree is None or self.pq is None:
              self.load()
          pq = PyQuery(tree, css_translator=PDFQueryTranslator()) if tree is not None else self.pq
          if tree is None:
              pq = self.pq
          else:
              pq = PyQuery(tree, css_translator=PDFQueryTranslator())
          results = []
          formatter = None
          parent = pq
          for search in searches:
              if len(search) &lt; 3:
                  search = list(search) + [formatter]
              key, search, tmp_formatter = search
              if key == 'with_formatter':
                  if isinstance(search, basestring): # is a pyquery method name, e.g. 'text'
                      formatter = lambda o, search=search: getattr(o, search)()
                  elif hasattr(search, '__call__') or not search: # is a method, or None to end formatting
                      formatter = search
                  else:
                      raise TypeError("Formatter should be either a pyquery method name or a callable function.")
              elif key == 'with_parent':
                  parent = pq(search) if search else pq
              else:
                  try:
                      result = parent("*").filter(search) if hasattr(search, '__call__') else parent(search)
                  except cssselect.SelectorSyntaxError, e:
                      raise cssselect.SelectorSyntaxError( "Error applying selector '%s': %s" % (search, e) )
                  if tmp_formatter:
                      result = tmp_formatter(result)
                  results += result if type(result) == tuple else [[key, result]]
          if as_dict:
              results = dict(results)
          return results
  
  
  
  
  
      # tree building stuff
  
      def get_pyquery(self, tree=None, page_numbers=[]):
          """
              Wrap given tree in pyquery and return.
              If no tree supplied, will generate one from given page_numbers, or all page numbers.
          """
          if tree is None:
              if not page_numbers and self.tree is not None:
                  tree = self.tree
              else:
                  tree = self.get_tree(page_numbers)
          if hasattr(tree, 'getroot'):
              tree = tree.getroot()
          return PyQuery(tree, css_translator=PDFQueryTranslator())
  
      def get_tree(self, *page_numbers):
          """
              Return lxml.etree.ElementTree for entire document, or page numbers given if any.
          """
          cache_key = "_".join(map(str, _flatten(page_numbers)))
          tree = self._parse_tree_cacher.get(cache_key)
          if tree is None:
              # set up root
              root = parser.makeelement("pdfxml")
              if self.doc.info:                           #not all PDFs seem to have this info section
                  for k, v in self.doc.info[0].items():
                      root.set(k, unicode(v))
              # add pages
              if page_numbers:
                  pages = [[n, self.get_layout(self.get_page(n))] for n in _flatten(page_numbers)]
              else:
                  pages = enumerate(self.get_layouts())
              for n, page in pages:
                  page = self._xmlize(page)
                  page.set('page_index', unicode(n))
                  page.set('page_label', self.doc.get_page_number(n))
                  root.append(page)
              self._clean_text(root)
              # wrap root in ElementTree
              tree = etree.ElementTree(root)
              self._parse_tree_cacher.set(cache_key, tree)
          return tree
  
      def _clean_text(self, branch):
          """
              Remove text from node if same text exists in its children.
              Apply string formatter if set.
          """
          if branch.text and self.input_text_formatter:
              branch.text = self.input_text_formatter(branch.text)
          try:
              for child in branch:
                  self._clean_text(child)
                  if branch.text and branch.text.find(child.text) &gt;= 0:
                      branch.text = branch.text.replace(child.text, '', 1)
          except TypeError: # not an iterable node
              pass
  
  
      def _xmlize(self, node, root=None):
  
          # collect attributes of current node
          tags = self._getattrs(node, 'y0', 'y1', 'x0', 'x1', 'width', 'height', 'bbox', 'linewidth', 'pts', 'index','name','matrix','word_margin' )
          if type(node) == LTImage:
              tags.update( self._getattrs(node, 'colorspace','bits','imagemask','srcsize','stream','name','pts','linewidth') )
          elif type(node) == LTChar:
              tags.update( self._getattrs(node, 'fontname','adv','upright','size') )
          elif type(node) == LTPage:
              tags.update( self._getattrs(node, 'pageid','rotate') )
  
          # create node
          branch = parser.makeelement(node.__class__.__name__, tags)
          branch.layout = node
          self._elements += [branch] # make sure layout keeps state
          if root is None:
              root = branch
  
          # add text
          if hasattr(node, 'get_text'):
              branch.text = node.get_text()
  
          # add children if node is an iterable
          if hasattr(node, '__iter__'):
              last = None
              for child in node:
                  child = self._xmlize(child, root)
                  if self.merge_tags and child.tag in self.merge_tags:
                      if branch.text and child.text in branch.text:
                          continue
                      elif last is not None and last.tag in self.merge_tags:
                          last.text += child.text
                          last.set('_obj_id', last.get('_obj_id')+","+child.get('_obj_id'))
                          continue
                  # sort children by bounding boxes
                  if self.resort:
                      _append_sorted(root, child, _comp_bbox)
                  else:
                      branch.append(child)
                  last = child
  
          return branch
  
      def _getattrs(self, obj, *attrs):
          """ Return dictionary of given attrs on given object, if they exist, processing through filter_value(). """
          return dict( (attr, unicode(self._filter_value(getattr(obj, attr)))) for attr in attrs if hasattr(obj, attr))
  
      def _filter_value(self, val):
          if self.round_floats:
              if type(val) == float:
                  val = round(val, self.round_digits)
              elif hasattr(val, '__iter__'):
                  val = [self._filter_value(item) for item in val]
          return val
  
  
  
      # page access stuff
  
      def get_page(self, page_number):
          """ Get PDFPage object -- 0-indexed."""
          return self._cached_pages(target_page=page_number)
  
      def get_layout(self, page):
          """ Get PDFMiner Layout object for given page object or page number. """
          if type(page) == int:
              page = self.get_page(page)
          self.interpreter.process_page(page)
          return self.device.get_result()
  
      def get_layouts(self):
          """ Get list of PDFMiner Layout objects for each page. """
          return (self.get_layout(page) for page in self._cached_pages())
  
      def _cached_pages(self, target_page=-1):
          """
              Get a page or all pages from page generator, caching results.
              This is necessary because PDFMiner searches recursively for pages,
              so we won't know how many there are until we parse the whole document,
              which we don't want to do until we need to.
          """
          try:
              # pdfminer &lt; 20131022
              self._pages_iter = self._pages_iter or self.doc.get_pages()
          except AttributeError:
              # pdfminer &gt;= 20131022
              self._pages_iter = self._pages_iter or PDFPage.create_pages(self.doc)
  
          if target_page &gt;= 0:
              while len(self._pages) &lt;= target_page:
                  next = self._pages_iter.next()
                  if not next:
                      return None
                  next.page_number = 0
                  self._pages += [next]
              try:
                  return self._pages[target_page]
              except IndexError:
                  return None
          self._pages += list(self._pages_iter)
          return self._pages
  
  
  if __name__ == "__main__":
      import doctest
      pdf = PDFQuery("../examples/sample.pdf")
      doctest.testmod(extraglobs={'pdf': pdf}, optionflags=doctest.ELLIPSIS)
  </code></pre>