import os
import fitz
if __name__ =='__main__':
pdf_path = r'your/path/to/sample.pdf'
doc = fitz.open(pdf_path)
save_path ='your/path/to/pdf-to-images'# Making it if the save_path is not exist.
os.makedirs(save_path, exist_ok=True)for page in doc:
pix = page.get_pixmap(alpha=False)
pix.save(f'{save_path}/{page.number}.png')print('PDF convert to images successfully!')
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
4. PDF 转 Word 文档
同样地,请确保你的环境已安装了必要的库 pdf2docx。如果未安装,通过 pip install pdf2docx 命令安装即可。下面这个简单的示例脚本通过 pdf2docx 实现 PDF 转 Word 文档。请将输入和输出文件路径替换成你自己的。
from pdf2docx import Converter
def convert_pdf_to_word(input_pdf, output_docx):
# Create a PDF converter object
pdf_converter = Converter(input_pdf)# Convret the PDF to a docx file
pdf_converter.convert(output_docx)# Close the converter to release resources
pdf_converter.close()if __name__ =='__main__':
input_pdf = r'material_sets/12-SQL-cheat-sheet.pdf'
output_docx = r'material_sets/12-SQL-cheat-sheet.docx'
convert_pdf_to_word(input_pdf, output_docx)print('The PDF file has been successfully converted to Word format!')
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
图片
原 PDF 文件:
图片
转换为 Word 文档:
图片
如果你细心观察的话,转换后,内容格式没有发生任何变化。Nice!👍
代码实现逻辑:
从 pdf2docx 库导入 Converter 类。
定义 convert_pdf_to_word 函数,以输入 PDF 文件路径和输出 DOCX 文件路径作为参数。
使用输入 PDF 文件路径创建一个 PDF 转换器对象。
调用 convert 方法将 PDF 转换为 DOCX 格式。
调用 close 方法关闭转换器以释放资源。
最后在程序入口(__main__)模块,定义输入 PDF 文件路径和输出 DOCX 文件路径,然后调用上面定义的 convert_pdf_to_word 函数执行转换操作。