#!/opt/local/bin//perl

#
# This perl script take a pdf file and split it vertically into two (+/- 5%)
# It can be usefull when two opposite pages where scanned at the same time.
#  _____ _____        _____ 
# |     |     |      |     |____
# |  1  |  2  |  --> |  1  |    |
# |     |     |      |     | 2  |
# |_____|_____|      |_____|    |
#                         |_____|  
#
# This code comes without any warranty. Use it to your own risk.
#
# Input: "file.pdf", output: "file_split.pdf"
#
# Dependence: PDF::API2
#
# 08/2008 - GIBELIN J. -
#

use PDF::API2;

if($#ARGV<0){
    print "Usage $0 [-margin=X%]input_file  [output_file]\n" ;
    exit(0);
}

$margin = .0 ; # safety marging in percent
$file = "" ;
foreach(@ARGV){
    $a = $_ ;
    if($a =~ /\-margin=(.*)%/){
        $margin = $1/100. ;
    } elsif($a =~ /(.*)(\.pdf|\.PDF)/ && $file eq ""){
        $file = $a ;    
        $name = $1 ;
        $outfile = $name."_split.pdf" ;
    } elsif($a =~ /(.*)(\.pdf|\.PDF)/ && $file ne ""){
        $outfile = $a ;
    }
}

print "Input file: $file\n";
print "Output file: $outfile\n";
print "Cut with a ".($margin*100)."% margin\n";


$pdfin = PDF::API2->open($file);
$pdfout = PDF::API2->new;

for($i=1;$i<=$pdfin->pages;$i++){
    @mbox = $pdfin->openpage($i)->get_mediabox();
#left
    $page = $pdfout->importpage($pdfin,$i); 
    $page->mediabox(@mbox);
    $page->cropbox(0,0,$mbox[2]*(.5+$margin),$mbox[3]);
#right
    $page = $pdfout->importpage($pdfin,$i); 
    $page->mediabox(@mbox);
    $page->cropbox($mbox[2]*(.5-$margin),0,$mbox[2],$mbox[3]);

}
$pdfout->saveas($outfile);
