Github上Python转PDF软件源码

电脑技术 电脑技术 856 人阅读 | 0 人回复 | 2022-04-07

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. from logging import NOTSET
  2. from pathlib import WindowsPath
  3. from tkinter import *
  4. from tkinter import messagebox
  5. from tkinter import filedialog
  6. import os, sys, subprocess
  7. from tkinter import font
  8. from typing import Sized
  9. from PIL import ImageTk, Image
  10. import fnmatch
  11. import docx2pdf
  12. import img2pdf
  13. import PyPDF2
  14. from fpdf import FPDF
  15. from docx2pdf import convert
  16. from time import sleep
  17. from tkinter import Tk, Label

  18. window = Tk()
  19. window.resizable(False, False)
  20. window.geometry("600x400")
  21. window.title("PDF Converter")
  22. window.config(background="#6495ed")
  23. # pop.resizable(False, False)

  24. paths = []
  25. files = []
  26. # to get the location of the current python file
  27. global basedir
  28. basedir = os.path.dirname(os.path.abspath(__file__))

  29. #file chosing function
  30. def chooseFiles():
  31.     global filepath
  32.    
  33.     filepath = filedialog.askopenfilename(initialdir="../", title="Select File :",
  34.     filetypes=(("Available Files","*.jpg png jpeg raw svg heic docx txt"), ("All Files", "*.*")))
  35.    
  36.     global filename
  37.     filename = os.path.basename(filepath)
  38.     files.append(filepath)

  39.     global frame
  40.    
  41.     frame = Frame(window, bg="#ffffff")

  42.     frame.place(relx=0.38, rely=0.4, width=355, height=135,)

  43.     yscrollbar = Scrollbar(frame, orient=VERTICAL)
  44.     yscrollbar.pack(side=RIGHT, fill=Y)

  45.     xscrollbar = Scrollbar(frame, orient=HORIZONTAL)
  46.     xscrollbar.pack(side=BOTTOM, fill=X)

  47.     fbox = Canvas(frame,width=355, height=135, scrollregion=(0, 0, 500, 500),
  48.            xscrollcommand=xscrollbar.set, yscrollcommand=yscrollbar.set, bg='white')
  49.     fbox.pack()
  50.    
  51.     yscrollbar.config(command=fbox.yview)
  52.     xscrollbar.config(command=fbox.xview)
  53.    
  54.     if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.svg')):
  55.         i = 10;  
  56.         for file in files:
  57.             selectedimage = Label(fbox, text=file, bg="#bed8f4")
  58.             selectedimage.pack()
  59.             fbox.create_window(235, i, window=selectedimage)
  60.             i+=25
  61.             
  62.     else:
  63.         global filelogo
  64.         filelogo = PhotoImage(file=os.path.join(basedir,"media/file.png"))
  65.         for file in files:
  66.                
  67.                 selectedfile = Label(frame,
  68.                                     text=filename,
  69.                                     bg="#fff",
  70.                                     fg="#828282",
  71.                                     image=filelogo,
  72.                                     compound=TOP      
  73.                                 )
  74.                 selectedfile.place(relx=0,
  75.                                 rely=0.01,
  76.                                 width=350,
  77.                                 height=130,
  78.                                 )
  79.                
  80. #save to path function
  81. def savePath():
  82.     global spath
  83.     spath = filedialog.askdirectory()

  84.     paths.append(spath)
  85.     # print(spath)

  86.     # for path in paths:
  87.     destination = Label(canvas,
  88.                                 text="Save to : " + spath,
  89.                                 bg="#2f4a7c",
  90.                                 fg="#fff",
  91.                                 padx=6.5,
  92.                                 image=saveTo,
  93.                                 compound=LEFT
  94.                             )
  95.     destination.place(rely=0.85, relx=0.01)

  96. #files to pdf
  97. def filetopdf():
  98.         try:
  99.             filepath
  100.         except NameError:
  101.             messagebox.showwarning("Warning", "You must choose a file first")
  102.         else:
  103.             if(filename.lower().endswith(('.png', '.jpg', '.jpeg', '.svg'))):
  104.                 imgtopdf()
  105.             if(filename.lower().endswith('.txt')):
  106.                 txtTopdf()
  107.             if(filename.lower().endswith('.docx')):
  108.                 docxTOpdf()
  109.         refresh()
  110.         

  111. def refresh(self):
  112.     self.destroy()
  113.     self.__init__()
  114.     filetopdf.update()

  115. #img to pdf function
  116. def imgtopdf():
  117.         nn = entry.get()
  118.         global name     
  119.         name = nn
  120.         if(name==""):
  121.             messagebox.showwarning("ERROR", "Your new PDF file need a name!!")
  122.         else:
  123.         #####
  124.             try:
  125.                 spath
  126.             except NameError:
  127.                 messagebox.showwarning("Warning", "You must choose a path to save the file")
  128.                 os.close()
  129.             else:     
  130.                 with open(f"{spath}/{name}.pdf","wb") as f:
  131.                     print(f"{spath}/{name}")
  132.                     f.write(img2pdf.convert(files))
  133.                 try:
  134.                     name
  135.                 except NameError:
  136.                     messagebox.showwarning("Warning","Your pdf file was saved without a name")
  137.                 else:
  138.                     complete()
  139.                     os.close()     
  140.            
  141. #docx to pdf
  142. def docxTOpdf():
  143.         nn = entry.get()
  144.         global name
  145.         name = nn
  146.         #####   
  147.         try:
  148.            spath
  149.         except NameError:
  150.             messagebox.showwarning("Warning", "New PDF file need a new path to save")
  151.             # spath = "../Document/)"
  152.         else:
  153.             with open(f"{spath}/{name}.pdf","wb") as f:
  154.                 newdf = os.path.join(spath,name)
  155.                 f.write(docx2pdf.convert(filepath, f"{spath}/{name}.pdf"))
  156.                 # os.system('loading.py')
  157.             complete()
  158.             os.close()


  159. #text file to pdf
  160. def txtTopdf():
  161.     pdf = FPDF()
  162.     nn = entry.get()
  163.     global name
  164.     name = nn
  165.     if(name==""):
  166.         messagebox.showwarning("Warning", "Your New PDF file will be saved with a defult name")
  167.         name = filename
  168.     else:
  169.         try:
  170.             spath
  171.         except NameError:
  172.                 messagebox.showwarning("Warning", "New PDF file need a new path to save")
  173.                 # spath = "../Document/)"
  174.         else:  
  175.             pdf.add_page()
  176.         
  177.             pdf.set_font("Arial", size = 12)
  178.             # open the text file in read mode
  179.             f = open(f"{filepath}", "r")
  180.             # insert the texts in pdf
  181.             for x in f:
  182.                 pdf.multi_cell(w=0,h=10, txt = x, align = 'L')
  183.             # save the pdf with name .pdf
  184.             # loadingSplash()
  185.             pdf.output(f"{spath}/{name}.pdf")
  186.             
  187.             if(name!=""):
  188.                 complete()
  189.   
  190. #remove array[]
  191. def removefiles():
  192.     print ("Before", files)
  193.     files.clear()
  194.     for widgets in frame.winfo_children():
  195.       widgets.destroy()
  196.     print ("After", files)
  197.    

  198. #alert messages
  199. def complete():
  200.     messagebox.showinfo("ALl Set","Congrats! Your PDF is ready")
  201. def warning():
  202.     messagebox.showwarning("All Set!","Your PDF was saved without a name!")
  203. # def den():
  204. #     name = filename
  205. #     messagebox.showwarning("Warning", "Your New PDF file will be saved with a defult name")
  206.    
  207. #foregrounds frames

  208. logo = PhotoImage(file=os.path.join(basedir,'media/logo.png'))

  209. #header and logo
  210. header = Label(window,
  211.                     text="Convert Your Files To .PDF",
  212.                     fg="#111111" ,font=("Arial", 20, 'bold'),
  213.                     bg="#6495ed",
  214.                     pady=5,
  215.                     image=logo,
  216.                     compound=TOP,
  217.                     )
  218. header.place(relx=0.27, rely=0.05)

  219. #second frame
  220. canvas = Canvas(window,
  221.                     width=580,
  222.                     height=230,
  223.                     bg="#2f4a7c"
  224.                     )
  225. canvas.place(rely=0.35, relx=0.01)

  226. #buttons
  227. chooseFile = Button(canvas,
  228.                         text="Choose File",
  229.                         bg='white', fg='black',
  230.                         padx=50,
  231.                         pady=5,
  232.                         command=chooseFiles
  233.                         )
  234. chooseFile.place(relx=0.025, rely=0.1)

  235. saveTo = PhotoImage(file=os.path.join(basedir,"media/saveto.png"))
  236. savePath = Button(canvas,
  237.                         text="Save Destination",
  238.                         bg='white', fg='black',
  239.                         padx=35,
  240.                         pady=5,
  241.                         command=savePath,
  242.                         )
  243. savePath.place(relx=0.025, rely=0.3)

  244. convert = Button(canvas,
  245.                         text="Convert",
  246.                         bg='white', fg='black',
  247.                         padx=62,
  248.                         pady=5,
  249.                         command=filetopdf
  250.                         )
  251. convert.place(relx=0.025, rely=0.5)

  252. remove = Button(canvas,
  253.                         text="Remove",
  254.                         bg='white', fg='black',
  255.                         padx=62,
  256.                         pady=5,
  257.                         command=removefiles
  258.                         )
  259. remove.place(relx=0.025, rely=0.7)

  260. #Labels
  261. global preview
  262. preview = Label(canvas,
  263.                         text="Drag and Drop your files",
  264.                         bg="#fff",
  265.                         fg="#828282",      
  266.                 )
  267. preview.place(relx=0.38,
  268.                 rely=0.1,
  269.                 width=350,
  270.                 height=130,
  271.                 )
  272. newfileas = Label(canvas,
  273.                     text="Save File As : ",
  274.                     bg="#2f4a7c",
  275.                     fg="#fff"
  276.                     )
  277. newfileas.place(relx=0.38, rely=0.7)

  278. global entry
  279. entry = Entry(width=20, background="#3a4c77", fg="#fff",border=None)
  280. entry.place(relx=0.55, rely=0.75)


  281. browse = Label(canvas,
  282.                     text="Save to : ",
  283.                     bg="#2f4a7c",
  284.                     fg="#fff",
  285.                     padx=5,
  286.                     image=saveTo,
  287.                     compound=LEFT
  288.             )
  289. browse.place(rely=0.88, relx=0.01)

  290. # if __name__ == '__main__':
  291. window.mainloop()
  292. sys.exit()
复制代码


您需要登录后才可以回帖 登录 | 立即注册

本版积分规则