Welcome folks today in this post we will be merging images to pdf document
using pypdf2
library in python. All the full source code of application is shown below.
Get Started
First of all you need to install the following library using the pip
command as shown below
pip install pypdf2
In order to get started you need to make an app.py
file and copy paste the following code
app.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
from tkinter import * from tkinter import filedialog from PIL import ImageTk, Image from PyPDF2 import PdfFileWriter, PdfFileReader img_list = [] root = Tk() root.title('Opening files') def open_file(): global page root.filename = filedialog.askopenfilenames(initialdir=".s", title="Select a file", filetypes=( ("PNG Files", "*.png"), ("All files", "*.*"))) file_list = list(root.filename) for name in file_list: page = Image.open(name) page = page.convert("RGB") img_list.append(page) my_label = Label(text=name).pack() def generate_pdf(): global page global img_list page.save(r"Gone with the Blastwave.pdf", save_all=True, append_images=img_list) print(img_list) # def stop(): # exit() my_button = Button(root, text="Add file", command=open_file).pack() my_button2 = Button(root, text="Generate PDF", command=generate_pdf).pack() my_button3 = Button(root, text="Cancel", command=exit).pack() root.mainloop() pages_to_delete = [0] # page numbering starts from 0 infile = PdfFileReader('New_File.pdf', 'rb') output = PdfFileWriter() for i in range(infile.getNumPages()): if i not in pages_to_delete: p = infile.getPage(i) output.addPage(p) with open('New_File.pdf', 'wb') as f: output.write(f) |
Now if you execute the python
script by typing the below command as shown below
python app.py