当前位置:   article > 正文

python: 从pdf中提取图片_fitz api xreflength

fitz api xreflength

fitz库:提取pdf中的图片,超好用的!

针对python 3.10
利用fitz库读取文件:

import fitz
file = 'test.pdf'
doc = fitz.open(file)

  • 1
  • 2
  • 3
  • 4

获得doc的对象数:

lenXREF = doc.xref_length()
  • 1

遍历每一个对象,并打印:

for i in range(1, nums):
	# 定义对象字符串
	text =  doc.xref_object(i);
	print(i, text)
	

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

import fitz
import time
import re
import os

#1.使用正则表达式查找PDF中的图片
def pdfTOpic(path,pic_path):#path:pdf的路径,pic_path:图片保存的路径
    t0 = time.perf_counter() #python 3.8已经不支持time.clock了
    #使用正则表达式来查找图片
    checkXO = r"/Type(?= */XObject)"
    checkIM = r"/Subtype(?= */Image)"
    #打开pdf
    doc = fitz.open(path)
    #图片计数
    imgCount = 0
    lenXREF = doc.xref_length()

    #打印pdf的信息
    print("文件名:{},页数:{},对象:{}".format(path,len(doc),lenXREF-1))

    #遍历每一个对象
    for i in range(1,lenXREF):
        #定义对象字符串
        text = doc.xref_object(i)
        isXObject = re.search(checkXO,text)
        #使用正则表达式查看是否是图片
        isImage = re.search(checkIM,text)
        #如果不是对象也不是图片,则continue
        if not isXObject or not isImage:
            continue
        imgCount+=1
        #根据索引生成图像
        pix = fitz.Pixmap(doc,i)
        #根据pdf的路径生成图片的名称
        new_name = path.replace('\\','_')+"_img{}.png".format(imgCount)
        new_name = new_name.replace(':','')

        #如果pix.n<5,可以直接存为png
        if pix.n<5:
            pix.writePNG(os.path.join(pic_path,new_name))
        #否则先转换CMYK
        else:
            pix0 = fitz.Pixmap(fitz.csRGB,pix)
            pix0.writePNG(os.path.join(pic_path,new_name))
            pix0 = None
        #释放资源
        pix = None
        t1 = time.perf_counter()
        print("运行时间:{}s".format(t1-t0))
        print("提取了{}张图片".format(imgCount))

if __name__ == '__main__':
    #pdf路径
    path = r'E:\PythonExperiment\Numerial.pdf'
    #创建保存图片的文件夹
    pic_path = r'E:\PythonExperiment\extractPictrue'
    if os.path.exists(pic_path):
        print("文件夹已存在,请重新创建文件夹!")
        raise SystemExit
    else:
        os.mkdir(pic_path)
    m=pdfTOpic(path,pic_path)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/51674
推荐阅读
相关标签
  

闽ICP备14008679号