|
| 1 | +from pdfrw import PdfWriter, PdfReader |
| 2 | +import os |
| 3 | + |
| 4 | + |
| 5 | +def delete(path, del_page): |
| 6 | + """ |
| 7 | + The function delete takes two arguments path and del_page |
| 8 | + path is the path of the source pdf file. |
| 9 | + This function deletes the pages from the pdf file. |
| 10 | +
|
| 11 | + Parameters: |
| 12 | + path : Path of the pdf file. |
| 13 | + del_page : A list of pages to be deleted. |
| 14 | +
|
| 15 | + Returns: |
| 16 | + None |
| 17 | + """ |
| 18 | + # create a pdf object using PdfReader that could be read |
| 19 | + pdf_obj = PdfReader(path) |
| 20 | + # pdf_obj.pages attribute gives the length of the pages in pdf |
| 21 | + total_pages = len(pdf_obj.pages) |
| 22 | + print("Total Pages in PDF are:", total_pages) |
| 23 | + # Initialising the writer object using the PdfWriter class |
| 24 | + writer = PdfWriter() |
| 25 | + |
| 26 | + # Adding only those pages that we need to this list excluding del_page |
| 27 | + page_list = [page for page in range( |
| 28 | + 1, total_pages+1) if page not in del_page] |
| 29 | + |
| 30 | + # Index of pdf_obj.pages starts from 0. |
| 31 | + for page in page_list: |
| 32 | + writer.addpage(pdf_obj.pages[page-1]) |
| 33 | + |
| 34 | + # removing the original pdf |
| 35 | + os.remove(path) |
| 36 | + # writing the modified file to the memory |
| 37 | + writer.write(path) |
| 38 | + |
| 39 | + |
| 40 | +path = input("enter the path(full or relative) of the pdf file:") |
| 41 | +del_page = input( |
| 42 | + "Enter the pages to be deleted seperated by comma(,):").strip().split(",") |
| 43 | +del_page = [int(i) for i in del_page] |
| 44 | +delete(path, del_page) |
| 45 | +print("\n\t pages", *del_page, "have been deleted successfully!!!") |
0 commit comments