python3 pdf 转 txt
程序员文章站
2022-04-11 10:29:39
...
平时用手机看书,很多都是pdf格式的,手机阅读器没办法重新排版,看着不舒服,索性自己些个小程序把PDF转换成txt,在此记录一下,欢迎大家赐教指正
代码很简单,直接贴出来吧
from pdfminer.pdfinterp import PDFResourceManager, process_pdf
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from io import StringIO
from io import open
def readPDF(pdfFile):
rsrcmgr = PDFResourceManager()
retstr = StringIO()
laparams = LAParams()
device = TextConverter(rsrcmgr, retstr, laparams=laparams)
process_pdf(rsrcmgr, device, pdfFile)
device.close()
content = retstr.getvalue()
retstr.close()
return content
def saveTxt(txt):
with open("istxt.txt", "w") as f:
f.write(txt)
txt = readPDF(open('ispdf.pdf', 'rb'))
saveTxt(txt)
使用的是python3,记得提前安装PDFminer3K。
pip install PDFminer3K
对于纯文本的转换还是不错的,如果是带有图片或者表格的PDF效果不是很理想