首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用PyM从pdf中提取文件时遇到的问题

用PyM从pdf中提取文件时遇到的问题
EN

Stack Overflow用户
提问于 2022-07-28 12:38:12
回答 1查看 222关注 0票数 0

我想提取和保存图像为.png,从一个pdf文件。我使用以下Python代码和PyMuPDF:

代码语言:javascript
运行
复制
import fitz 
import io
from PIL import Image
file = "pdf1.pdf"
pdf_file = fitz.open(file)
for page_index in range(len(pdf_file)):
    page = pdf_file[page_index]
    image_list = page.getImageList()

    if image_list:
        print(f"[+] Found a total of {len(image_list)} images in page {page_index}")
    else:
        print("[!] No images found on page", page_index)
    for image_index, img in enumerate(page.getImageList(), start=1):
    
        xref = img[0]
        base_image = pdf_file.extractImage(xref)
        image_bytes = base_image["image"]
        image_ext = base_image["ext"]
        image = Image.open(io.BytesIO(image_bytes))
        image.save(open(f"image{page_index+1}_{image_index}.{image_ext}", "wb"))

但我得到以下错误消息:

代码语言:javascript
运行
复制
---------------------------------------------------------------------------
  AttributeError                            Traceback (most recent call last)
  <ipython-input-5-bb8715bc185b> in <module>()
  10     # get the page itself
  11     page = pdf_file[page_index]
  ---> 12     image_list = page.getImageList()
  13     # printing number of images found in this page
  14     if image_list:

  AttributeError: 'Page' object has no attribute 'getImageList'

​是否与pdf文件结构(非字典类型)有关?在那种情况下我该怎么解决呢?

EN

Stack Overflow用户

回答已采纳

发布于 2022-08-03 09:42:51

您忘了提到您使用的PyMuPDF版本。您的方法名称getImageList已经被废弃了很长时间了--应该使用新的名称page.get_images()。在最新版本1.20.x中,旧名称最终被删除。如果您有大量使用这些旧名称的旧代码,可以使用实用程序进行全局更改,或者在import fitz之后执行fitz.restore_aliases()

票数 1
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73153059

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档