Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chuyển ảnh sang PDF dùng Tkinter

Python ngôn ngữ script giúp tạo converter: CSV to PDF, PDF to DOC, ngược lại. Với thư viện, tạo ứng dụng chuyển ảnh sang PDF. Dùng module img2pdf Python. Parse binary ảnh chuyển thành PDF.

Các bước:

  • Đảm bảo hệ thống có img2pdf. pip install img2pdf terminal cài gói. Import img2pdf.
  • Import filedialog mở dialog chọn nhiều ảnh.
  • Import tkinter bằng from tkinter import *.
  • Tạo cấu trúc cơ bản Tkinter: Button mở File Dialog, Label thông báo.
  • Định nghĩa hàm mở dialog chọn nhiều ảnh.
  • Định nghĩa hàm mở file binary chuyển PDF dùng convert.

Ví dụ

# Import required Libraries
from tkinter import *
from tkinter import filedialog
import img2pdf
from tkinter import ttk
# Create instance tkinter frame
win = Tk()
#set geometry
win.geometry('750x250')
win.title("Image to PDF")
def select_file():
    global images
    images = filedialog.askopenfilenames(initialdir = "",title = "Select Images")
    Label(win, text=images).pack()
#Convert Image to PDF
def image_to_pdf():
    for image in enumerate(images):
        with open(f"{image}.pdf", "wb") as file:
            file.write(img2pdf.convert(images))
            Label(frame,text=file).pack()
# Add Labels and Buttons
Label(win, text = "Image to PDF Convertor",font = "Caveat 25 bold").pack(pady = 30)
ttk.Button(win, text = "Select Images",command = select_file).pack(ipadx = 10)
frame = Frame(win)
frame.pack()
ttk.Button(frame, text = "Convert and Save",command = image_to_pdf).pack(side = LEFT, pady=20,ipadx = 10)
win.mainloop()

Kết quả

Chạy mã hiển thị cửa sổ ứng dụng chuyển ảnh sang PDF.

Chuyển ảnh sang PDF dùng Tkinter

Chọn file ảnh, bấm "Convert and Save" chuyển lưu PDF.