Search code examples
batch-filepdftk

PDFTK right click to encrypt


I need to get a certain part of the file name and use that as a variable in a batch file.

Each file will have the following structure: "name_surname$code".

My goal is to get all text after the $ sign.

While being smacked on the fingers with good reason for the neglect relating to 'best practice', I unfortunately do not know another way past this issue.

avery_larry assisted me in getting the code right in my batch file (see code below), but now I want to take things further by adding it to the right click/send to command.

Here is my code for the batch file (although this does not work for the right click option).

The example below loops through all files, whereas the code I need now should only apply to the files selected.

@ECHO OFF

setlocal EnableDelayedExpansion
md out
for /f %%G in ('dir /b "*.pdf"') do (
    for /f "delims=$ tokens=1*" %%H in ("%%~nG") do set "partial_filename=%%~I"
    call:_pwgen passwd
    set FULLNAME=%%G
    set ENDTEXT=!FULLNAME:*$=!
    call set TRIMMEDNAME=%%FULLNAME:!ENDTEXT!=%%
    pdftk %%G output out/!TRIMMEDNAME:~0,-1!.pdf user_pw !passwd!
)

goto :EOF

:_pwgen passwd
setlocal ENABLEEXTENSIONS
set passwd=%~1
set _count=0:_loop
set /a _count+=1
set passwd=%partial_filename%
endlocal&set %~1=%passwd%
GOTO:EOF

Solution

  • That was not entirely what I needed.

    With a lot of reading and breaking my batch file a lot of times, I found the answer I was looking for.

    SETLOCAL ENABLEDELAYEDEXPANSION
    @echo off
    if [%1]==[] goto :eof
    :loop
    
    set var=%~n1
    
    for /f "tokens=1 delims=*$" %%a in ("%var%") do set "partial_filename=%%~I (
        set _string=!var%:*$=!
    )
    for /f "tokens=1 delims=$*" %%a in ("%var%") do  set "partial_filename=%%~I (
        set _fname=!var%:$*=!
    )
    call set _newfname=%%_fname:!_string!=%%
    
    pdftk %1 output "%~dp1!_newfname:~0,-1!%~x1" user_pw !_string! allow printing
    shift
    if not [%1]==[] goto loop