Sample Header Ad - 728x90

Using Ghostscript to extract every nth page from PDF

2 votes
2 answers
2794 views
I don't know if this can be done, I'm just learning ghostscript. Say I have multiple PDF files each about 500 Pages in length. Can I setup ghostscript to go extract every 100 pages from each document and save each as a separate PDF file? So I have FileA.pdf, 500 Pages in Length. So I'd now want **FileA_0001.pdf FileA_0002.pdf FileA_0003.pdf FileA_0004.pdf FileA_0005.pdf** I've managed to write a script that will split files and merge them based on my interval, I'm having trouble trying to rename files properly. The issue I've run into is after it finishes splitting and merging after the first file it will rename it as **FileA_0001.pdf FileA_0002.pdf FileA_0003.pdf FileA_0004.pdf FileA_0005.pdf** However the problem is once it begins the process for FileB, it does this **FileB_0006.pdf FileB_0007.pdf** I've tried a few different ways, but each have failed, advice? Can someone assist?
for file in /mnt/bridge/pdfsplit/staging/*.[pP][dD][fF]
do
  echo $file
  #Splits All the Files
  gs -q -dNOPAUSE -sDEVICE=pdfwrite -o tmp_%04d.pdf $file
  
  #Removes Last File in List; Ghostscript creates a blank file everytime it splits
  find /mnt/bridge/pdfsplit/ -name "tmp*"  | tail -1 | while read filename ; do rm $filename; done
  
    pageCount=$(find . -name "tmp*" | wc -l)
    documents=$(((pageCount / 998) + (pageCount % 998 > 0)))
    pages=$(((pageCount/documents) + (pageCount % documents > 0 )))
  
    for ((i=1; i/dev/null | head -$pages)
      count=$(ls -1 tmp* 2>/dev/null| wc -l)
      gs -q -dNOPAUSE -sDEVICE=pdfwrite -o $(basename $file .pdf )_Part_$(printf %04d $i).pdf -dBATCH $list
      rm -f $list
      if [[ $count -eq 0 ]]; then
          echo "Done"
          break
          fi
    done
            
    
    #Removes Last File in List; Ghostscript is creating a blank file
    mv *.pdf /mnt/bridge/pdfsplit/splitFiles/
    find /mnt/bridge/pdfsplit/splitFiles/ -name "*.pdf"  | tail -1 | while read filename ; do rm $filename; done

done
Asked by Josh Adams (83 rep)
Mar 20, 2019, 07:20 PM
Last activity: May 24, 2025, 08:05 AM