Manipulate PDF files (read, split, combine, move)

Question:

I’m trying to figure out a way to deal with scanned pdf’s with either Python or PHP. I need to be able to open a multiple page PDF, read the contents, and move the pages to individual PDF files (or one file if they are to be grouped) based on an identifier in the text.

I downloaded and have played around a little bit with pdftotext, but am unsure whether that is the best way to go. I used a sample scanned PDF, ran it through pdftotext to a txt file and grepped around it a bit. It works OK; I was able to find some identifiers, but will need moar regex skill for it to be efficient. But I’m hung at splitting the PDF’s up and moving them based on pdftotext.

Any ideas?


Edit: clarification.

  1. Use pdftotext to spit out each page of pdf to individual txt files;
  2. grep the txt files for identifiers and compile a list of those pages that are similar;
  3. based on the list extract and combine (if applicable) related pages and spit out a pdf of each;
  4. move generated PDF based on grouping to another location;

PyPDF seems to be a good place to start. This is what I have so far:

from pyPdf import PdfFileWriter, PdfFileReader
import re

output = PdfFileWriter()
input1 = PdfFileReader(file("test.PDF", "rb"))
totalPages = input1.getNumPages()
print "total pages to process:" +str(totalPages)

for i in range(totalPages):
    p = i
    print "processing page %s" %str(i)
    output.addPage(input1.getPage(p))
    p = input1.getPage(p).extractText()#extract text to search for identifier
    pr = re.search("identifier", p)#search for the identifier; to be replaced with a list
    #if there's a match, do work
    if pr:
        outputStream = file("test"+str(i)+".pdf", "wb")
        output.write(outputStream)
        outputStream.close()
        print 'match on page %s' %str(i)
        print 'n'

Then from here I can use another library to consolidate PDF’s based on their location.

Another question, though: how robust is Python’s re.search function? Especially dealing with shady OCR, can it be reliable?

Asked By: stormdrain

||

Answers:

I’ve used pypdf with success on small projects.

Answered By: lafras

Have you tried pypdf?

And here is a recipe using pypdf to extract the text: http://code.activestate.com/recipes/511465-pure-python-pdf-to-text-converter/

Answered By: payne
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.