python读取word/pdf文档,指定文字内容和图片

读编号转文件夹目录然后放图片进去那个


一 先将word转为PDF

pdf 读起来比较方便, 按页码读取文件:

import pdfplumber
from PIL import Image
import cv2
import numpy as np
import re
import os
import logging
import io


def create_folder(folder_name):
    if not os.path.exists(folder_name):
        os.makedirs(folder_name)


def CountPages(file_path):
    """
    根据编号创建文件夹
    :param file_path:
    :return:
    """
    with pdfplumber.open(file_path) as pdf:
        count = 0
        for page in pdf.pages:
            count += 1
            print(f"----------- 第{count}页 ----------- \n\n")

            text = page.extract_text()
            matches = re.findall(r'编号\s*(\S+)', text)

            if matches:
                for match in matches:
                    if '*' in match:
                        logging.warning(f'编号名称存在不能使用的字符,需要单独调整,Page {count}, 编号后面的内容: {match}')
                        folder_name = 'new_files/' + f'000 error Page_{count}'
                        # continue
                    else:
                        # folder_name = './new_files/' + match
                        folder_name = './new_files/' + f'{count}_' + match
                    create_folder(folder_name)

            images = page.images
            print(f'images: {images}')
            for i, img in enumerate(images):
                # x0, y0, x1, y1 = img["x0"], img["y0"], img["x1"], img["y1"]
                img_stream = img["stream"]

                # 从流中提取图像数据
                img_data = img_stream.get_data()

                # 使用数据创建新图像
                pil_img = Image.open(io.BytesIO(img_data))

                # 将图像保存为 JPG
                img_filename = f"{folder_name}/image_{count}_{i + 1}.jpg"
                pil_img.save(img_filename, format="JPEG")
                print(f"保存图像:{img_filename}")

        return count


"""
    1 需要先将文档转换为 pdf
    2 文件夹名称不要页码改 39 行
    3 编号最好不要出现 * 这种不能作为文件名的符号
    4 filePath 改文件路径
    5 保存文件在同级文件目录下
"""

# filePath = r"E:\11-normal_program\registration_card.pdf"
filePath = r"./registration_card.pdf"
CountPages(filePath)

猜你喜欢

转载自blog.csdn.net/March_A/article/details/132313774