def pdf_to_img():
print("请输入pdf文件路径")
# 需要转换的pdf文件路径
pdfPath = tkinter.filedialog.askopenfilename()
father_path = os.path.abspath(os.path.dirname(pdfPath) + os.path.sep + ".")
doc = fitz.open(pdfPath)
imgFile = father_path + '\\img'
if(os.path.exists(imgFile)):
shutil.rmtree(imgFile)
os.mkdir(imgFile)
print("正在转换中~~~~")
pageCount = 100/doc.pageCount
beilv = pageCount
for pg in range(doc.pageCount):
print(str(round(pageCount, 2)) + '%')
pageCount += beilv
page = doc[pg]
rotate = int(0)
# 每个尺寸的缩放系数为2,这将为我们生成分辨率提高四倍的图像。
zoom_x = 2.0
zoom_y = 2.0
trans = fitz.Matrix(zoom_x, zoom_y).preRotate(rotate)
pm = page.getPixmap(matrix=trans, alpha=False)
pm.writePNG(imgFile + '\\%s.png' % pg)
return imgFile
def convertImg():
# pdf转换成一个一个图片的图片存放路径
imgPath = pdf_to_img()
print("已完成pdf转换至图片的任务~")
# 转换成功后的文件路径
wordFile = tkinter.filedialog.asksaveasfilename()
APP_ID = "23403595"
API_KEY = "MIvoIhkmsYHPiA2LOZmSu3o3"
SECRET_KEY = "E063BVdf2kemnjF4hv9lcG0Xg5Of065k"
client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
imgs = os.listdir(imgPath)
if not os.path.exists(wordFile):
os.mknod(wordFile)
wordFileName = open(wordFile, 'w')
processCount = 100/len(imgs)
beilv = processCount
print("正在将文字存至电脑中~~~")
for img in imgs:
print(str(round(processCount, 2)) + '%')
processCount += beilv
dakai = open(imgPath + "/" + img, "rb")
duqu = dakai.read()
message = client.basicGeneral(duqu)
for duqu in message.get("words_result"):
words = duqu.get("words")
wordFileName.write(words)
wordFileName.write("\r\n")
if (os.path.exists(imgPath)):
shutil.rmtree(imgPath)
print("完成")
if __name__ == '__main__':
convertImg()
python简单实现pdf转图片再转文字
最新推荐文章于 2023-12-17 15:35:57 发布