使用带有抛光字符的pyPDF2读取pdf

时间:2018-02-12 15:24:33

标签: python file pdf encode pypdf2

我正在尝试使用PyPDF2库来读取由波兰字符组成的pdf文件(例如ń,ś等),但在使用extractText()函数后,输出字符串缺少波兰人。有没有办法仍然使用PyPDF2库但首先正确编码,解码pdf文件? 我试图用encoding ='utf-8'和'latin-1'打开文件,但没有成功。谢谢你的帮助!

代码段:

file = open(myPDFfile, "rb")
pdfreader = PyPDF2.PdfFileReader(file, strict=True)
page_obj = pdfreader.getPage(0)
page_txt = page_obj.extractText()
page_txt_split = page_txt.split()

1 个答案:

答案 0 :(得分:0)

好的,我以不同的方式处理它。由于jmcarp github我使用pdfminer使用UTF-8编码从我的pdf文件中提取文本,一切正常(没有丢失任何抛光字符)。我发布了工作代码的片段:

from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfpage import PDFPage
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from cStringIO import StringIO


def pdf_to_text(pdfname):
    # PDFMiner boilerplate
    rsrcmgr = PDFResourceManager()
    sio = StringIO()
    device = TextConverter(rsrcmgr, sio, codec='utf-8', laparams=LAParams())
    interpreter = PDFPageInterpreter(rsrcmgr, device)
      # get text from file
    fp = file(pdfname, 'rb')
    for page in PDFPage.get_pages(fp):
        interpreter.process_page(page)
    fp.close()
      # Get text from StringIO
    text = sio.getvalue()
      # close objects
    device.close()
    sio.close()

    return text