一聚教程网:一个值得你收藏的教程网站

热门教程

Python实现文字pdf转换图片pdf效果代码示例

时间:2022-06-25 01:18:09 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下Python实现文字pdf转换图片pdf效果代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

代码展示

先安装依赖

pip install PyMuPDF

输入文件列表

import os
import fitz


def single_wordpdf_to_imgpdf(pdf_path: str):
    pdf = fitz.open(pdf_path)   # 打开pdf目录
    pdf_img = fitz.open()       # 打开空文件,用来存图片pdf
    for page_inf in pdf:
        definition = 3    # 清晰度,感觉输出的pdf不够清晰,可以调大,调大,文件大小也会变大
        matrix = fitz.Matrix(definition, definition)
        img = page_inf.get_pixmap(matrix=matrix).tobytes()
        img = fitz.open("png", img)
        pdf_bytes = img.convert_to_pdf()
        pdf_img.insert_pdf(fitz.open("pdf", pdf_bytes))
    pdf_img.save("图片pdf_" + os.path.basename(pdf_path))


def group_wordpdf_to_imgpdf(path_array: list[str]):
    for pdf_path in path_array:
        print(pdf_path, "转换中...")
        single_wordpdf_to_imgpdf(pdf_path)
    print("完成")


if __name__ == '__main__':
    path = ["xxx.pdf"]
    group_wordpdf_to_imgpdf(path)

输入文件夹

import os
import fitz
import time


def single_wordpdf_to_imgpdf(pdf_path: str):
    pdf = fitz.open(pdf_path)   # 打开pdf目录
    pdf_img = fitz.open()       # 打开空文件,用来存图片pdf
    for page_inf in pdf:
        definition = 3    # 清晰度,感觉输出的pdf不够清晰,可以调大,调大,文件大小也会变大
        matrix = fitz.Matrix(definition, definition)
        img = page_inf.get_pixmap(matrix=matrix).tobytes()
        img = fitz.open("png", img)
        pdf_bytes = img.convert_to_pdf()
        pdf_img.insert_pdf(fitz.open("pdf", pdf_bytes))
    if not os.path.exists("output"):
        os.makedirs("output") # 处理好的pdf存入了output目录下 #
    pdf_img.save("output/图片pdf_" + os.path.basename(pdf_path))


def group_wordpdf_to_imgpdf(path_array: list[str]):
    for pdf_path in path_array:
        print(pdf_path, "转换中...")
        single_wordpdf_to_imgpdf(pdf_path)
    print("完成")


def folder_pdf_files(folder: str) -> list[str]:  # 一个文件夹里面有多少pdf文件
    file_list = []
    for a, b, c in os.walk(folder):
        if b == []:
            for filename in c:
                if filename[-3:].lower() == 'pdf':
                    file_path = os.path.join(a, filename)
                    file_list.append(file_path)
    print(folder, ": 有", len(file_list), "个pdf文件")
    return file_list


if __name__ == '__main__':
    time_start = time.time()
    path_list = folder_pdf_files("目录")
    group_wordpdf_to_imgpdf(path_list)
    time_end = time.time()
    print("程序运行时间:", round(time_end - time_start, 2), "秒")

热门栏目