本篇内容主要讲解“Python怎么实现文字pdf转换图片pdf效果”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Python怎么实现文字pdf转换图片pdf效果”吧!
代码展示
先安装依赖
pip install PyMuPDF
输入文件列表
import osimport fitzdef 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 osimport fitzimport timedef 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_listif __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), "秒")
到此,相信大家对“Python怎么实现文字pdf转换图片pdf效果”有了更深的了解,不妨来实际操作一番吧!这里是编程网网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!