Split PDF, name odd pages and name even pages in sequence

I need help creating a script to ask the user for a PDF file then do the following:

-Extract even pages and rename name with "_Front#" ending where "#" is a number sequence starting with 1.

→ ex: the PDF I choose when prompted is "anatomyBook". The extracted even pages would be:

- anatomyBook_Front1, anatomyBook_Front2, anatomyBook_Front3,...

-Extract odd pages and name them similarly except replace "Front" with "Back"


Thanks for the help!

Posted on Jul 31, 2014 4:08 PM

Reply
20 replies

Aug 2, 2014 10:40 PM in response to kevnm67

Hello


Here's a revised script which accepts multiple input files and optional output directory as arguments. You may pass input files by shell glob such as *.pdf as shown below.


Note that you may NOT quote the glob (filename matching) characters such as * in shell, otherwise it is treated as literal character without special meaning. Please pay close attention to the usage of "quoted form" of AppleScript in the following example, which will properly quote the path that may contain characters to be quoted such as spaces etc whilst it will not quote the glob character *.




set infile to (path to desktop)'s POSIX path's quoted form & "test/*.pdf" -- => "'/Users/your-user-name/Desktop/'test/*.pdf"
set outdir to (path to desktop)'s POSIX path & "test/out" -- => "/Users/your-user-name/Desktop/test/out"

do shell script "/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby -w <<'EOF' - " & infile & " " & outdir's quoted form & "
# 
#     ARGV = pdf [pdf ...] [output_directory]
#     
require 'osx/cocoa'
OSX.require_framework 'PDFKit'
include OSX

def usage
    raise ArgumentError, \"Usage: #{File.basename($0)} pdf [pdf ...] [output_directory]\"
end

usage unless ARGV.length > 0
outdir = File.directory?(ARGV.last) ? ARGV.pop : nil
usage unless ARGV.length > 0

ARGV.select { |f| File.file?(f) }.each do |f|
    url = NSURL.fileURLWithPath(f)
    doc = PDFDocument.alloc.initWithURL(url)
    unless doc
        $stderr.puts \"Not a pdf file: %s\" % [File.expand_path(f)]
        next
    end
    bname = File.basename(f).sub(/\\.pdf$/i, '')
    odir = outdir ? outdir : File.dirname(f) 
    front, back = '_Front', '_Back'
    
    (0 .. (doc.pageCount - 1)).each do |i|
        page = doc.pageAtIndex(i)
        doc1 = PDFDocument.alloc.initWithData(page.dataRepresentation)
        doc1.writeToFile(\"#{odir}/#{bname}#{i % 2 == 0 ? front : back}#{i / 2 + 1}.pdf\")
    end
end
EOF"



Regards,

H

Aug 3, 2014 7:44 AM in response to Hiroto

Awesome! Thank you.


Last question:

Im using the script in my cocoa app but get a crash on this line:

desc = [scptexecuteAndReturnError: &errdict];

Any thoughts? just wondering if I'm missing something. Should I be importing a framework to successfully run the script?




-(void)runScriptToSplitPDF {

NSDictionary *errdict;

NSAppleEventDescriptor *desc;

NSString *path = [[NSBundlemainBundle] pathForResource:@"PDFscript"ofType:@"scpt"];

NSURL *url = [NSURL fileURLWithPath: path];

NSAppleScript *scpt = [[NSAppleScriptalloc] initWithContentsOfURL: urlerror: &errdict];

if (!scpt)

fprintf(stderr, "Failed to load script: %s\n", [[errdictdescription] UTF8String]);

else

{

desc = [scptexecuteAndReturnError: &errdict];

// [scpt release];

if (!desc)

fprintf(stderr, "Runtime error in script: %s\n", [[errdictdescription] UTF8String]);

}

[selfmakeFlashCards:self];

}

Aug 4, 2014 3:59 AM in response to kevnm67

Hello


NSAppleScript is part of Foundation framework. Since your code is compiled fine, framework dependencies are already resolved.


Do you see anything suspicious in console log? And what does the crash log say?



As far as I can tell, the following test programme works as expected under 10.6.8.


/*    
    file
        main.m
    
    function
        run compiled applescript
    
    compile
        gcc -framework Foundation -o run_applescript main.m

    usage e.g.
        ./run_applescript a.scpt
*/

#import <Foundation/Foundation.h>
#include <libgen.h>    // basename

int
main(int argc, char **argv)
{
    if ( argc != 2 )
    {
        fprintf(stderr, "Usage: %s <compiled applescript>\n", basename(argv[0]));
        return 1;
    }
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    NSString *path = [NSString stringWithUTF8String: argv[1]];
    NSURL *url = [NSURL fileURLWithPath: path];
    NSDictionary *errdict;
    NSAppleEventDescriptor *desc;
    NSAppleScript *scpt = [[NSAppleScript alloc] initWithContentsOfURL: url error: &errdict];
    if (!scpt)
        fprintf(stderr, "Failed to load script: %s\n", [[errdict description] UTF8String]);
    else
    {
        desc = [scpt executeAndReturnError: &errdict];
        [scpt release];
        if (!desc)
            fprintf(stderr, "Runtime error in script: %s\n", [[errdict description] UTF8String]);
        else
            fprintf(stdout, "%s\n", [[desc description] UTF8String]);
    }
    
    [pool release];
    return 0;
}



Regards,

H


EDIT: fixed typo

Aug 7, 2014 10:55 PM in response to kevnm67

Hmm. I wonder what your actual applescript is.


The error:


Could not connect the action moveToFolder: to target of class AppDelegate



would indicate it is not plain applescript and if so, I doubt NSAppleScript can execute it. To my understanding, AppleScriptObjC script needs to be processed by NSBundle (AppleScriptObjectiveC) -loadAppleScriptObjectiveCScripts and only works in that context.


H


PS. If you're actually trying to run AppleScriptObjC script from your Objective-C programme, please start new thread on it because it has nothing to do with your original question about PDF processing.

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

Split PDF, name odd pages and name even pages in sequence

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.