开发者

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

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 开发者_如何学JAVAa 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?


I've used pypdf with success on small projects.


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜