Search code examples
batch-filepdftk

Windows Batch File to Read textfile and append for pdftk


I have a text file which contains the location of a list of pdf files. I am writing a windows batch file that needs to read this line by line and append in a command which will be executed to merge all the pdfs into 1 pdf using pdftk.

Below is the example command:

pdftk "C:\test\1.pdf" "C:\test\2.pdf"......"C:\test\50.pdf" cat output merged.pdf

I came across this How do you loop through each line in a text file using a windows batch file? for reading text file.

But how do I read and append to a variable which can then be used for the command mentioned above?


Solution

  • Assuming your list of pdf files looks like this

    pdf1.pdf
    pdf2.pdf
    pdf3.pdf
    

    Then you can use this to concatenate them into one variable

    setlocal enabledelayedexpansion
    set files=
    for /f "tokens=*" %%a in (pdfs.txt) do (
    if defined files (
    set files=!files! "%%a"
    ) else (
    set files="%%a"
    )
    )
    pdftk !files! cat output merged.pdf
    

    The if else is there to remove the leading space from the variable, I wasn't sure if that would make a difference. If it doesn't then you can get rid of it and just use

    setlocal enabledelayedexpansion
    set files=
    for /f "tokens=*" %%a in (pdfs.txt) do (    
    set files=!files! "%%a"
    )
    pdftk !files! cat output merged.pdf