【发布时间】:2020-06-23 16:26:49
【问题描述】:
我正在尝试从目录 (path) 中读取 PDF 文件,以从每个 PDF 中提取单个图像并写入同一目录。但是,我无法对每个文件执行以下功能,因为我的脚本只解析目录中的最后一个文件。我正在使用的代码如下所示:
pip install pymupdf
import os
import PyPDF2
import fitz # from pymupdf
import glob
path = "C:\\Users\\mdl518\\Desktop\\"
def pdf_extract():
for filename in glob.glob(os.path.join(path, "*.pdf"), recursive=True): # file path specifying the location of the PDF files
with open(os.path.join(os.getcwd(), filename),'rb') as f: # open/read the PDF files
pdf_document=fitz.open(filename)
for current_page in range(len(pdf_document)): # iterate over the total number of pages in each PDF
for image in pdf_document.getPageImageList(current_page):
xref=image[0] # initiates the cross-reference number for objects on the first page of the PDF
pix=fitz.Pixmap(pdf_document, xref)
if pix.n < 5: # capture all images and write to the file path
pix.writeImage(os.path.join(path,"page%s-%s.jpg") % (current_page, xref))
else:
pix1 = fitz.Pixmap(fitz.csRGB, pix)
pix1.writeImage(os.path.join(path,"page%s-%s.jpg") % (current_page, xref))
pix1 = None
pix = None
pdf_extract()
我曾尝试使用glob、os.listdir() 和os.walk() 来解析单个 PDF,但我得到的最好的方法是从最后一个 PDF 文件中提取图像以读取/写入文件路径.有没有更简单的方法来解决这个问题,或者它只是对我的“glob”声明的一个小调整?非常感谢任何帮助!
【问题讨论】:
标签: python loops automation directory pdf-parsing