Skip to content

Instantly share code, notes, and snippets.

@goerz
Created August 1, 2010 18:47
Show Gist options
  • Save goerz/503628 to your computer and use it in GitHub Desktop.
Save goerz/503628 to your computer and use it in GitHub Desktop.
scan.pl: A script that wraps sane to scan to a pdf file, A4, black-and-white.
#!/usr/bin/perl -w
use strict;
use threads;
# (c) 2007 Michael Goerz <[email protected]>
# usage:
# scan [pdffile]
# Prerequisites:
# iText (http://www.lowagie.com/iText/)
# unpaper (http://unpaper.berlios.de/)
# pnm2tif (http://netpbm.sourceforge.net/)
# paper size constants
my @a4 = ("210mm", "297mm");
my @custom = ("170mm", "250mm");
my $dpi = 300;
my ($xsize, $ysize) = @a4;
my $itext = "/home/goerz/bin/iText/iText.jar";
# Preparation
my $outputfile = '';
if (@ARGV > 0){
$outputfile = shift;
}
my $scanpath = '/tmp/scan'.`date +%F_%k-%M`;
chomp $scanpath;
$scanpath =~ s/[ ]//;
system("mkdir $scanpath");
my @threads;
# Scanning
my $i = 1;
print "Press 'Enter' for next scan. Press 'Ctrl+D' to finish\n\n";
print "Put in Page $i ";
while(my $input = <>){
my $file = sprintf("$scanpath/scan%04d.pnm", $i);
my $execstring = "scanimage --format=pnm --mode Lineart --resolution $dpi -x $xsize -y $ysize > $file";
system($execstring);
printf("Done: Page %i. Put in Page %i ", $i, $i+1);
$threads[$i-1] = threads->new(\&postprocess, $file);
$i++;
}
print "\nDone with scanning...\n";
# catch all running threads
foreach my $thread (@threads){
$thread->join;
}
# PDF Conversion
print("\n\nConverting to pdf....\n");
if ($outputfile eq ''){
$outputfile = askoutput();
}
system ("java -cp $itext com.lowagie.tools.plugins.PhotoAlbum $scanpath \"$outputfile\"");
print "\nFile saved as $outputfile\n\n";
# Cleaning up
my $deltempfiles = deletetempfiles();
if ($deltempfiles == 1){
system("rm $scanpath/*.tif");
system("rmdir $scanpath");
}
print("\n");
sub postprocess{
my $file = shift;
#system "unpaper -l single -dr 4 \"$file\" \"$file.out\" >/dev/null 2>&1";
system "cp \"$file\" \"$file.out\"";
system "pnmtotiff -resolutionunit=inch -xresolution $dpi -yresolution $dpi \"$file.out\" > \"$file.tif\"";
if (-f "$file.tif"){
unlink($file);
unlink("$file.out");
}
}
sub askoutput{
print "Where do you want to save the pdf file? [$scanpath/scan.pdf] ";
my $answer = <STDIN>;
if ($answer eq ''){
$answer = "$scanpath/scan.pdf";
}
print "\n";
return $answer;
}
sub deletetempfiles{
print "Do you want to delete the temporary TIF files? [Yes]/No ";
my $answer = <STDIN>;
if ($answer eq 'No'){
return 0;
} else {
return 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment