#! /usr/bin/env python

import sys
import pdb
import logging
import argparse

import PyPDF2

parser = argparse.ArgumentParser(description='Trying out PyPDF2 to read Adobe Acrobat documents')
parser.add_argument('-v', '--verbose', action='count', help='Enable debugging')
args = parser.parse_args()

logging.basicConfig(format='%(asctime)s %(levelname)s %(pathname)s:%(lineno)d %(msg)s')
log = logging.getLogger()
# log.setLevel(logging.DEBUG if args.verbose else logging.WARNING)
log.setLevel(logging.WARNING - (args.verbose or 0)*10)

assert not sys.stdin.isatty(), 'stdin must be redirected'

pdf = PyPDF2.PdfFileReader(sys.stdin, warndest=open('/dev/null', 'w'))

log.info('There are {} pages'.format(pdf.numPages))

for pagenum in range(pdf.numPages):
  page = pdf.getPage(pagenum)
  """
    Text can be broken up by newlines at curious places.  There is no break in the PDF document when you view it, there is no
    hyphen when a word is interrupted.  Fortunately, if a word is broken in the middle, there will not be a intervening blank so
    we can break up the original string into a list of strings using newlines as the separators and we can then join the list back
    together using empty strings.
  """
  text = ''.join(page.extractText().splitlines())
  log.debug('{pagenum}: {text!r}'.format(**locals()))
