#!/usr/bin/env python

# pdfGrep - Search for keywords in PDF files
#
# Written by Lucas C. Villa Real <lucasvr@gobolinux.org>
# Released under the GNU GPL version 2.

# Dependencies: 
# Poppler         http://poppler.freedesktop.org
# Poppler-Python  https://launchpad.net/poppler-python

import os
import poppler

if len(os.sys.argv) < 3 :
	print "Syntax: %s <keyword> <pdf file(s)>" %os.sys.argv[0]
	os.sys.exit(1)

def statusLine(text) :
	return "\033[1m" + text + "\033[0m"

def highlight(line, keyword) :
	hkeyword = "\033[01;31m" + keyword + "\033[0m"
	return line.replace(keyword, hkeyword)

def pdfGrep(pdffile, keyword) :
	basefile = os.path.basename(pdffile)
	doc = poppler.document_new_from_file("file://"+pdffile, None)
	if not doc :
		print "Error: could not open document %s." %pdffile
		os.sys.exit(1)

	num_pages = doc.get_n_pages()
	for i in range(0,num_pages) :
		page = doc.get_page(i)
		match = page.find_text(keyword)
		for m in match :
			line = page.get_text("line", m).split("\n")
			print "%s%s" %(statusLine("%s, page %d:" %(basefile,i+1)), highlight(line[0], keyword))

keyword = os.sys.argv[1]
for f in os.sys.argv[2:] :
	pdffile = os.path.realpath(f)
	pdfGrep(pdffile, keyword)
