Python 提取pdf的首尾页并转成图片

合同PDF有很多页,需要提取首页和尾页(盖章页),并转成图片,以便检查有无未盖章的合同,借用了几位网友的代码,重构了一下。

转图片须先安装poppler:

https://github.com/oschwartz10612/poppler-windows/releases/download/v23.07.0-0/Release-23.07.0-0.zip

并将...poppler-23.07.0\Library\bin 放入系统环境变量的PATH中

import os

from PyPDF2 import PdfReader, PdfWriter
from pdf2image import convert_from_path

src_dir = "D:\\files\\bk\\src_pdf\\"
out_dir = "D:\\files\\bk\\output_pdf\\"
pic_dir = "D:\\files\\bk\\output_pic\\"


def list_all_file_names(root_dir):
    file_name_dict = []
    files = os.listdir(root_dir)
    for i in range(0, len(files)):
        file_name = os.path.join(files[i])
        file_name_dict.append(file_name)
    return file_name_dict


def extract_first_and_last_page(filename):
    pdf_src_file = PdfReader(src_dir + filename)
    page_count = len(pdf_src_file.pages)
    filename = filename.replace(".pdf", "_1.pdf")
    output_file = out_dir + filename
    with open(output_file, "wb") as new_file:
        pdf = PdfWriter()
        pdf.add_page(pdf_src_file.pages[0])
        pdf.add_page(pdf_src_file.pages[page_count - 1])
        pdf.write(new_file)


def pdf_to_pic(pdf_name):
    images = convert_from_path(out_dir + pdf_name)
    for i, image in enumerate(images):
        new_pic_name = pic_dir + pdf_name + "_" + str(i) + '.jpg'
        image.save(new_pic_name, "JPEG")


src_pdf_names = list_all_file_names(src_dir)
print("src_pdf_names: ", src_pdf_names)
for name in src_pdf_names:
    extract_first_and_last_page(name)


out_pdf_names = list_all_file_names(out_dir)
print("out_pdf_names: ", out_pdf_names)
for new_pdf_name in out_pdf_names:
    pdf_to_pic(new_pdf_name)

你可能感兴趣的:(python,pdf,windows)