script_print / print_in_parts.pl

#!/usr/bin/perl -w
#
# Print given file in pieces 20 pages each (workaround
# for unknown bug in my printer)

package PrintMe;
use Moose;
use namespace::autoclean;
use PDF::API2;
use List::Util qw(min);
use autodie qw(:all);
with 'MooseX::Getopt';

has 'file' => (is => 'ro', isa=>'Str', required => 1,
               documentation => 'File to print');
has 'split' => (is => 'ro', isa=>'Int', required => 1,
                default => sub { 20 },
                documentation => 'Split every ... pages');
has 'since' => (is => 'ro', isa=>'Int', required => 1,
                default => sub { 1 },
                documentation => 'Start from page ...');
has 'verbose' => (is => 'ro', isa=>'Bool', required => 0, default => 0,
                  documentation => "Be more verbose");

sub run {
    my $self = shift;

    my $doc = PDF::API2->open($self->file);
    my $pages_count = $doc->pages;
    undef $doc;
    my $start = $self->since;
    while($start <= $pages_count) {
        my $end = min($start + $self->split - 1, $pages_count);
        $self->print_part($self->file, $start, $end);
        $start = $end + 1;
    }
}

sub print_part {
    my ($self, $filename, $since, $to) = @_;

    $self->wait_for_inactive_printer;

    print "Printing pages $since-$to from $filename\n";

    my $command = "lp -o media=a4 -o sides=two-sided-long-edge -P '$since-$to' '$filename'";
    print "Trying:\n$command\n" if $self->verbose;
    system($command);

}

sub wait_for_inactive_printer {
    my $self = shift;

    print "Waiting for printer inactivity...";

    while($self->printer_active()) {
        sleep(1);
    }

    print "READY\n";
}

sub printer_active {
    my $self = shift;

    print "Checking lpstat...\n" if $self->verbose;
    my $active = 0;
    open(my $fd, "lpstat |");
    while(<$fd>) {
        unless(/^$/) {
            $active = 1;
            print "    $_" if $self->verbose;
        }
    }
    close($fd);

    return $active;
}

###########################################################################
# Main
###########################################################################

package main;

my $app = PrintMe->new_with_options();
$app->run();
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.