旧代码不适用于新版本的PDFMiner

时间:2019-04-16 09:37:24

标签: python pdfminer

我已经“继承”了前同事的一个程序。该程序较早运行良好,但对我不起作用。原因是该同事使用了较旧的PDFMiner版本(我不知道它是哪个版本),而我有一个新版本。代码如下:

filpath=r"...."
rsrcmgr = PDFResourceManager()
retstr = StringIO()
laparams = LAParams()
device = PDFPageAggregator(rsrcmgr, laparams=laparams)
fp = open(filepath,'rb')
interpreter = PDFPageInterpreter(rsrcmgr,device)
parser = PDFParser(fp)
doc = PDFDocument()
parser.set_document(doc)
doc.set_parser(parser)
doc.initialize('') 

起初我有错误

doc = PDFDocument()
TypeError: __init__() missing 1 required positional argument: 'parser'. 

我将doc = PDFDocument()行更改为doc = PDFDocument(parser)。这可行,但现在我出现了错误

'PDFDocument' object has no attribute 'set_parser'

其中显然来自doc.set_parser(parser)行。 我现在该怎么办?

其他信息:旧程序中的导入行为

from pdfminer.pdfparser import PDFParser, PDFDocument

这现在不起作用,我不得不将其更改为两行

from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument

谢谢!

1 个答案:

答案 0 :(得分:0)

您看过docs吗?

from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfpage import PDFTextExtractionNotAllowed
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfdevice import PDFDevice

# Open a PDF file.
fp = open('mypdf.pdf', 'rb')
# Create a PDF parser object associated with the file object.
parser = PDFParser(fp)
# Create a PDF document object that stores the document structure.
# Supply the password for initialization.
document = PDFDocument(parser, password)
# Check if the document allows text extraction. If not, abort.
if not document.is_extractable:
    raise PDFTextExtractionNotAllowed
# Create a PDF resource manager object that stores shared resources.
rsrcmgr = PDFResourceManager()
# Create a PDF device object.
device = PDFDevice(rsrcmgr)
# Create a PDF interpreter object.
interpreter = PDFPageInterpreter(rsrcmgr, device)
# Process each page contained in the document.
for page in PDFPage.create_pages(document):
    interpreter.process_page(page)

从链接中逐字复制。