<?php
// take a bunch of PDF files from one folder, parse their filenames, create folders based
// on the parsed information and finally pass the files through pdfjam to crop them,
// sending new files to the appropriate previously created folders
// PDF source filenames are always in the format "YEAR-MM-DD Some Text.pdf" example: "2012-08-01 Recent Scan.pdf"
// 2 unix paths are passed in as arguments
putenv("TZ=America/Montreal"); // change time zone to Eastern
// trim the bogus first parameter - automator seems to pass a "-" as a parameter preceeding the actual params
array_shift ($argv);
// base path to the folders we'll later create and put files in
$baseFolder = $argv[0];
// source path to the PDF files to be manipulated
$pdfTempFolder = $argv[1];
$dirHandle = opendir($pdfTempFolder);
// read all (matching) filenames from the pdftempfolder
while( ($fileName = readdir($dirHandle)) !== false ) {
// (only build list of PDF files starting with "2"
if( (substr($fileName, strrpos($fileName, '.') + 1) == "pdf") && (substr($fileName,0,1) == "2" ) ) {
$pdfFiles[] = $fileName;
}
}
if ($pdfFiles) { // only try the loop if there were files listed
// loop through all the files ($currentFile) and move them to their new folder with new name
foreach ($pdfFiles as $currentFile) {
// grab the date from the begining of the filename so we can figure out the destination path
$currentShipDate = substr ($currentFile, 0, strpos ($currentFile, " ") );
// create the new filename from the rest of the filename
$cleanFileName = substr ($currentFile, strpos ($currentFile, " ") +1);
$yearFolder = date("Y", strtotime($currentShipDate) ); // 4-digit year, eg: "2012"
$dayFolder = date("M d", strtotime($currentShipDate) ); // 3 char month & 2 digit day, eg: "Aug 01"
// create new folders if they don't already exist
if (!is_dir("$baseFolder/$yearFolder"))
mkdir("$baseFolder/$yearFolder");
if (!is_dir("$baseFolder/$yearFolder/$dayFolder"))
mkdir("$baseFolder/$yearFolder/$dayFolder");
shell_exec ("pdfjam '$pdfTempFolder/$currentFile' --trim '0in 5.5in 0in 0in' --clip true
--papersize '{8.5in,5.5in}' --outfile '$baseFolder/$yearFolder/$dayFolder/$cleanFileName'");
echo "$baseFolder/$yearFolder/$dayFolder/$cleanFileName"."\n";
}
}
?>