Page 1 of 1

Automatic pdf merger for simular filenames

Posted: 08 Feb 2017 08:22
by kexet77
Hello fellow nerds,
Iam rather new to all this but trying to learn. Ofc Ive googled this but cant find anything that works the way i want. Hopefully I can get some tips and help here.


I have a large number of pdf files in a folder, named like this:
XX1001 - 23.pdf, XX1001 - 27.pdf, XX1002 - 23.pdf, XX1002 - 27.pdf, XX1003 - 23.pdf, XX1003 - 27.pdf and so on..

I want to merge files with simular names into one pdf file, like this: XX1001 - 23.pdf and XX1001 - 27.pdf into XX1001.pdf, XX1002 - 23.pdf and XX1002 - 27.pdf into XX1002.pdf and so on..

Ive tried this one:

Code: Select all

@echo off
setlocal enabledelayedexpansion

rem source root folder where to crawl pdfs.
set "source=c:\mydoc\pdf"

rem destination folder
set "destination=c:\mydoc\merged"

for /f "delims=" %%a in ('dir /b /s /ad /o:n "%source%"') do (
    set _pdffiles=
    for /f "delims=" %%i in ('dir /b /a-d /o:n "%%a\*.pdf"') do (
        set _pdffiles=!_pdffiles! "%%i"
        set "_outputpdf=%%~ni"
    )
    echo pdftk.exe !_pdffiles! cat output "%destination%\!_outputpdf:~0,6!.pdf"
)


It works but i need to have all files in folders with the same name, which i havent got..

How can I modify this for my needs?

Thx!

/Erik

Re: Automatic pdf merger for simular filenames

Posted: 19 Feb 2017 16:31
by Samir
Easiest way to get this working would be to copy/move those files to a single folder. Otherwise, this will grow in complexity.

Re: Automatic pdf merger for simular filenames

Posted: 25 Feb 2017 12:52
by pieh-ejdsch
Hello kexet,

This I have coined. Robocopy is used because in a folder without subfolders also the directory names are output.
You can use the Delayed Extension of Variables before processing the research loop, but it is not a good style to make it so.

Code: Select all

@echo OFF
setlocal disabledelayedexpansion

 rem source root folder where to crawl pdfs.
set "source=D:\ordner2"

 rem destination folder
set "destination=c:\mydoc\merged"

set "Similar=?"
set "out="
set "merge="
for /f "tokens=*" %%i in ('robocopy /L "%source%" ". only listing .\\" *.pdf /njh /fp /ns /nc /ndl /njs ^&echo ?'
)do ( set "in=%%~ni"
  setlocal enabledelayedexpansion
  set "in=!in:~0,6!"
  for /f "tokens=1-3delims=*" %%d in ("!in!*!similar!*!out!")do (
    endlocal
    if NOT %%d == %%e (
      if defined merge   echo  pdftk.exe %%f cat output "%destination%\%%e.pdf"
      set out="%%i"
      set "similar=%%d"
      set "merge="
    )else (
      set "merge=1"
      set out=%%f "%%i"
    )
  )
)


Phil