python读取pdf文档

复制代码
import io
import pdfplumber
from opencc import OpenCC
import fitz  # pymupdf
import os

file_path = '/document/pdf/xxx.pdf'
output_dir = '/classification/pdf/images'
#获取图片 demo
def extract_images_from_pdf(pdf_path, output_dir):
    # 确保输出目录存在
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    # 打开PDF文件
    doc = fitz.open(pdf_path)
    page_count = doc.page_count
    # 遍历PDF的每一页
    for page_num in range(page_count):
        page = doc.load_page(page_num)
        # 获取页面中的图片信息
        images = page.get_images(full=True)
        image_index = 0
        for img_index, img in enumerate(images):
            xref = img[0]
            base_image = doc.extract_image(xref)
            image_bytes = base_image["image"]
            image_ext = base_image["ext"]
            # 使用Pillow将图片保存到本地
            from PIL import Image
            image = Image.open(io.BytesIO(image_bytes))
            image_path = os.path.join(output_dir, f"image_{page_num + 1}_{image_index + 1}.{image_ext}")
            image.save(image_path)
            image_index += 1
    doc.close()


# 使用示例
extract_images_from_pdf(file_path, output_dir)


cc = OpenCC('t2s')
def read_pdf_with_pdfplumber(file_path):
    images = []
    with (pdfplumber.open(file_path) as pdf):
        num_pages = len(pdf.pages)
        print(f"Number of pages: {num_pages}")
        text = pdf.pages[0].extract_text()
        text = cc.convert(text)
        print(text)
# 示例用法
read_pdf_with_pdfplumber(file_path)
相关推荐
ch.ju1 分钟前
Java Programming Chapter 3——Default value of array
java·开发语言
2301_812539673 分钟前
golang如何使用Fiber高性能框架_golang Fiber框架入门教程
jvm·数据库·python
aini_lovee5 分钟前
STM32 上实现 SD 卡读取 JPEG 解码 TFT 显示
开发语言·stm32
2401_880071405 分钟前
html标签如何提升可访问性_aria-label与title区别【指南】
jvm·数据库·python
谙弆悕博士7 分钟前
【附C语言源码】C语言 栈结构 实现及其扩展操作
c语言·开发语言·数据结构·算法·链表·指针·
njsgcs8 分钟前
c# solidworks GetPartBox无法获得正确实体边界框原因
开发语言·c#·solidworks
2401_850491658 分钟前
如何管理多个监听器_listener.ora中非默认端口配置实战
jvm·数据库·python
2501_940041748 分钟前
游戏实战prompt
python·pygame
bandaoyu8 分钟前
【CUDA】store/load普通访存 vs 非临时(Non-Temporal)访存
java·开发语言·redis
YuanDaima20488 分钟前
图论基础原理与题目说明
数据结构·人工智能·python·算法·图论·手撕代码