PDF转图片或Word文档

因工作需要,经常要将PDF转换为图片,所以自己摸索使用Python写一个PDF转换器,现在分享出来,与大家一起交流。

一、功能:
1、将PDF文件转换为JPG图片;
2、将PDF文件转换为Word文档,若PDF文件是通过Word文档转换的,可完美转换为可编辑Word文档。
3、可选择多个文件或文件夹批量转换。

二、界面展示:
在这里插入图片描述
三、需要的第三方库:

pdf2docx==0.5.7
PyMuPDF==1.23.8

四、源代码;

import tkinter as tk
from tkinter import filedialog
import fitz
from pdf2docx import Converter
import os
import time
import threading
import ctypes
 
 
class PdfConverter:
 
    def __init__(self):
        self.root = tk.Tk()
        self.root.title('PDF转换器')
        self.root.geometry("500x300+350+250")
        #self.root.resizable(width=False,height=False)禁用最大化
        #self.root.overrideredirect(1)删除主窗口标题栏
        self.interface()
 
    def interface(self):
        """"界面编写位置"""
        self.Button0 = tk.Button(self.root, text="选择文件", command=self.multiple_files)
        self.Button0.grid(row=0, column=0, pady=20)
 
        self.Button0 = tk.Button(self.root, text="选择文件夹", command=self.single_folder)
        self.Button0.grid(row=0, column=1, pady=20)
 
        self.Button1 = tk.Button(self.root, text="转为图片", command=self.start_to_jpg)
        self.Button1.grid(row=0, column=2, pady=20)
 
        self.Button2 = tk.Button(self.root, text="转为Word", command=self.start_to_word)
        self.Button2.grid(row=0, column=3, pady=20)
 
        self.w1 = tk.Text(self.root, width=68, height=15)
        self.w1.insert('insert','说明:1、文件可单选或多选;文件夹下文件均需转换,可直接选择文件夹;\n      2、转换后文件保存位置为所选文件或文件夹位置。')
        self.w1.grid(row=1, column=0, columnspan=4, padx=10)
 
    def single_folder(self):
        '''获取单个文件夹'''
        path = filedialog.askdirectory() + '/'
        files_path = [os.path.join(path,i) for i in os.listdir(path) if os.path.splitext(i)[-1].lower() == '.pdf']
        if len(files_path) != 0:
            self.w1.delete('1.0',tk.END)
            self.w1.insert('insert','\n'.join(files_path))
 
    def multiple_files(self):
        '''获取多个文件'''
        path = filedialog.askopenfilenames(filetypes=[('All Files', '.PDF')])
        if len(path) != 0:
            self.w1.delete('1.0',tk.END)
            self.w1.insert('insert','\n'.join(path))
 
    def pdf_to_jpg(self):
        '''将PDF转换为图片'''
        start_time = time.time()
        for file in self.path_list:
            os.makedirs(os.path.splitext(file)[0],exist_ok=True) # 创建以PDF文件名命名的文件夹
            pdf = fitz.open(file) # 打开PDF文件
            temp = 0
            for pg in range(pdf.page_count):
                page = pdf[pg]
                temp += 1
                rotate = int(0)
                # 每个尺寸的缩放系数为2,这将为我们生成分辨率提高四倍的图像。
                zoom_x = 2
                zoom_y = 2
                trans = fitz.Matrix(zoom_x, zoom_y).prerotate(rotate)
                pm = page.get_pixmap(matrix=trans, alpha=False)
                pic_name = '{}.jpg'.format(temp)
                #拼接生成图片存放的文件路径
                pic_pwd = os.path.join(os.path.splitext(file)[0], pic_name)
                pm.save(pic_pwd)
            self.w1.insert('end','完成 %s 转换\n' % os.path.split(file)[1])
            #self.w1.insert(tk.INSERT,'\n')换行
        end_time = time.time()
        self.w1.insert('end','转换已完成,共用时 %.2f 秒' % ((end_time - start_time)))
         
    def start_to_jpg(self):
        #将路径字符串转换为列表,strip():去除字符串前后空格或特殊字符;split('\n'):将字符串转为列表,元素以换行符分割
        self.path_list = self.w1.get('1.0','end').strip().split('\n')
        self.w1.delete('1.0',tk.END)
        if os.path.isfile(self.path_list[0]):
            self.T = threading.Thread(target=self.pdf_to_jpg)
            self.T.setDaemon(True)
            self.T.start()
        else:
            self.w1.insert('insert','请选择文件或文件夹')
 
    def pdf_to_word(self):
        '''将PDF转换为WORD'''
        start_time = time.time()
        for file in self.path_list:
            docx_name = os.path.splitext(file)[0] + '.docx'
            cv = Converter(file)
            cv.convert(docx_name)
            cv.close
            self.w1.insert('end','完成 %s 转换\n' % os.path.split(file)[1])
            #self.w1.insert(tk.INSERT,'\n')换行
        end_time = time.time()
        self.w1.insert('end','转换已完成,共用时 %.2f 秒' % ((end_time - start_time)))
 
    def start_to_word(self):
        #将路径字符串转换为列表,strip():去除字符串前后空格或特殊字符;split('\n'):将字符串转为列表,元素以换行符分割
        self.path_list = self.w1.get('1.0','end').strip().split('\n')
        self.w1.delete('1.0',tk.END)
        if os.path.isfile(self.path_list[0]):
            self.T = threading.Thread(target=self.pdf_to_word)
            self.T.setDaemon(True)
            self.T.start()
        else:
            self.w1.insert('insert','请选择文件或文件夹')
 
 
if __name__ == '__main__':
    whnd = ctypes.windll.kernel32.GetConsoleWindow()
    if whnd != 0:
        ctypes.windll.user32.ShowWindow(whnd, 0)
        ctypes.windll.kernel32.CloseHandle(whnd)
    a = PdfConverter()
    #a.root.after(1000,a.pdf_to_jpg)
    a.root.mainloop()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值