Advertisement
rajath_pai

PDF page split

Apr 16th, 2024
539
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.55 KB | None | 0 0
  1. import fitz  # PyMuPDF
  2.  
  3. def split_pdf(input_pdf, ranges_and_names):
  4.     # Open the input PDF
  5.     pdf = fitz.open(input_pdf)
  6.    
  7.     for range_and_name in ranges_and_names:
  8.         range_and_name_parts = range_and_name.split(' ')
  9.         start_page, end_page = map(int, range_and_name_parts[0].split('-'))
  10.         output_pdf = f"{range_and_name_parts[1]}.pdf"  # Extract the name from the range
  11.        
  12.         # Create a new PDF writer
  13.         writer = fitz.open()
  14.        
  15.         # Add pages to the new PDF
  16.         for page_num in range(start_page - 1, end_page):
  17.             writer.insert_pdf(pdf, from_page=page_num, to_page=page_num)
  18.        
  19.         # Save the new PDF
  20.         writer.save(output_pdf)
  21.         print(f"PDF created: {output_pdf}")
  22.  
  23. # Page ranges and corresponding names
  24. ranges_and_names = [
  25.     "1-15 1_GENERAL_SURGERY_REVISION",
  26.     "16-25 2_GENERAL_SURGERY_2_&_SHOCK",
  27.     "26-35 3_TRAUMA",
  28.     "36-47 4_TRAUMA_2_AND_BURNS",
  29.     "48-61 5_BREAST_DISORDERS",
  30.     "62-73 6_THYROID_AND_PARATHYROID",
  31.     "74-85 7_GIT_1",
  32.     "86-93 8_GIT_2",
  33.     "94-110 9_GIT_3",
  34.     "111-126 10_GIT_4",
  35.     "127-139 11_HEPATOBILIARY",
  36.     "140-152 12_HEPATOBILIARY_2_&_PANCREAS",
  37.     "153-169 13_VASCULAR_SURGERY",
  38.     "170-188 14_HERNIA_THORAX_AND_SKIN",
  39.     "189-204 15_UROLOGY_1",
  40.     "205-217 16_UROLOGY_2",
  41.     "218-233 17_TRANSPLANT_PLASTIC_SURGERY_AND_ADRENAL",
  42.     "234-243 18_ORAL_CANCER_&_SALIVARY_GLANDS"
  43. ]
  44. # Input PDF
  45. input_pdf = 'name.pdf'
  46.  
  47. # Call the function to split the PDF
  48. split_pdf(input_pdf, ranges_and_names)
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement