Skip to content

Instantly share code, notes, and snippets.

@nemo-kaz nemo-kaz/PDFRenamer
Created Dec 21, 2013

Embed
What would you like to do?
PDFRenamer.groovy renames PDF file to the file by its Title metadata.
// PDF Renamer : Rename PDF file from the metadata Title
// 1: set PATH to pdftk
// 2: plase PDFRenamer.groovy (this file to same directory of pdftk )
// 3: move to the root of target PDF directory
// 4: start PDFRenamer.groovy in pdftk directory
@Grab('net.java.dev.jna:jna:3.4.0') // since Java does not have directory moving function
import com.sun.jna.*;
import com.sun.jna.win32.*;
// pdftk is a must http://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/
def pathToPdftk ="c:\\where\\tool\\exists\\pdftk"
interface Kernel32Library extends StdCallLibrary {
Kernel32Library INSTANCE = Native.loadLibrary("kernel32", Kernel32Library.class);
boolean SetCurrentDirectoryA(String dir);
}
new File(".").eachFileRecurse { file ->
if(file.name.endsWith("pdf")) {
println file.getPath() +" を調査中"
Kernel32Library.INSTANCE.SetCurrentDirectoryA(file.getParent())
"cmd /c echo InfoKey: Title > metadata.txt".execute().text
"cmd /c echo InfoValue: ZZZ >> metadata.txt".execute().text
"${pathToPdftk} ${file.getName()} dump_data output metadata.txt".execute().text
if (getTitle().size()>19) { // Al least 20 charas new file name should have.
println "${file.getName()} renamed to ${getTitle()} "
file.renameTo( new File(file.getParent()+"/${getTitle()}.pdf") )
}
}
}
///////////////////
def getTitle() {
nextLine=0
bookTitle=""
new File("metadata.txt").eachLine { file, count ->
if (nextLine==1) {
nextLine=0
bookTitle=file.toString().replaceAll(/InfoValue: (.*)/) {m0, m1 -> "${m1}" }
bookTitle=bookTitle.tr(' ','_')
}
if (file.toString() =~/Title$/) { nextLine=1}
}
return bookTitle
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.