Home > Mobile >  Batch for removing last 2 pages from PDF files on a folder
Batch for removing last 2 pages from PDF files on a folder

Time:03-15

I am using the PDFtk to remove last 2 pages of a bunch of PDF from a specific folder.

For removing it individually on a file, this code works perfectly fine as the last two pages are removed from original.pdf and a newly created reduced.pdf copy is created without the last two pages

@echo off
cd "C:\Program Files (x86)\PDFtk\bin"
start pdftk.exe C:\Desktop\long\original.pdf cat 1-r3 output C:\Desktop\short\reduced.pdf

pause

Fyi, the pdf files all have various alphanumeric filenames and a - as separator between filename words e.g. the-march-event-2022.pdf

What I need now is how to automate is so the script would go through each pdf file on the long folder and create a new copy with identical filename through the command into the short folder

CodePudding user response:

The task can be done with a batch file with only following single command line:

@for %%I in ("C:\Desktop\long\*.pdf") do @"C:\Program Files (x86)\PDFtk\bin\pdftk.exe" "%%I" cat 1-r3 output "C:\Desktop\short\%%~nxI" && echo Successfully processed "%%~nxI" || echo ERROR: Failed to process "%%~nxI"

This command line uses the Windows command FOR to process all PDF files in the specified folder. For each PDF file is executed pdftk with the fully qualified file name of the current PDF file as input file name and the file name extension with a different directory path as output file name. Run for /? in a command prompt window for help on this command.

There is output the success message on pdftk.exe exits with value 0. Otherwise the error message is output on pdftk.exe exits with value not equal 0.

The two @ are for suppressing the output of the FOR command line and of each executed pdftk command line on processing the PDF files in the specified folder.

Please see single line with multiple commands using Windows batch file for an explanation of the conditional operators && and ||.

  • Related