首页 > 解决方案 > 使用 pfdtk 批量转换 pdf 文件,但名称中带有空格

问题描述

我正在尝试合并大量具有相似数字的pdf文件

例如“NR 01234567_1.pdf”“NR 01234567_2.pdf”等在一个文件夹中,其中包含数千个类似的文件页面,每个文件名需要合并,例如“NR 01234567.pdf”

我使用下面的脚本对所有文件名中没有空格的文件都成功了(感谢这个论坛上一些非常有帮助的人),但它不适用于名称中的空格。

谁能帮我解决这个问题?

@echo off
setlocal EnableDelayedExpansion

rem Initialize (delete) "lastFile" and "fileList" variables
set "lastFile="
set "fileList="

rem Next line get the output of a "dir /B" command, that show file names *only*
rem "for /F" command execute the dir, get the output and divide each line in two "tokens" ("%%a" and "%%b")
rem with the first part before the "_" in "%%a" and the *rest* (including further "_") in "%%b"

for /F "tokens=1* delims=_" %%a in ('dir /B *.*') do (

   rem If the base file name changed...
   if "%%a" neq "!lastFile!" (

      rem Process previous file list;
      rem this "if" is just to avoid process the empty list the first time
      if defined fileList (
         pdftk !fileList! output !lastFile!.pdf
      )

      rem Reinitialize the new list
      set "lastFile=%%a"
      set "fileList=%%a_%%b"

   ) else (

      rem Append this file to current list
      set "fileList=!fileList! %%a_%%b"

   )

)

rem Process the last list
pdftk !fileList! output !lastFile!.pdf

标签: batch-filepdfmergepdftk

解决方案


我认为可能有一种更简单的方法来完成这项任务。我记得pdftk.exe有一个cat选项可以使用通配符/glob。因此,您可以使用该选项代替创建文件列表,而不是创建文件列表。

这是一个示例,(请先更改pdftk.exeon line的位置3,然后以保存 PDF 文件的目录作为当前目录运行它:

@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "tkPDF=P:\ath\To\pdftk.exe"
Set "lastPreName="
For /F "EOL=_ Tokens=*" %%G In ('Dir "*_*.pdf" /B /A:-D /O:N 2^> NUL
 ^| "%SystemRoot%\System32\findstr.exe" /I /R "^.[^_]*_[^_]*.pdf$"'
) Do For /F "Tokens=1,* Delims=_" %%H In ("%%~nG") Do (
    SetLocal EnableDelayedExpansion
    If /I Not "!lastPreName!" == "%%~H" (
        Echo="%tkPDF%" "%%~H_*%%~xG" cat output "%%~H%%~xG")
    EndLocal
    Set "lastPreName=%%~H")
Pause

如果您对输出感到满意,它目前只显示将要运行的命令,Echo=从 line中删除10,以及可选Pause的在线13


推荐阅读