RSS Git Download  Clone
Raw Blame History
package LIMS::Local::PDF;

use Moose;
has path => ( is => 'ro', isa => 'Str', required => 1);
has htmldoc => ( is => 'ro', isa => 'HTML::HTMLDoc', lazy_build => 1 );
__PACKAGE__->meta->make_immutable;

# use WKHTMLTOPDF; # input file => output file
use HTML::HTMLDoc;
use Data::Dumper;

sub make_pdf {
    my $self = shift;
    my $args = shift; # warn Dumper $args->{session}->id;
    
    my $htmldoc = $self->htmldoc;
    
    { # logo:
        my $logo = $self->path . '/images/logo.jpeg';
        $htmldoc->set_logoimage($logo);
        $htmldoc->set_header('.', '.', 'l'); # positions; '.' = null; 'l' = logo
    }
    { # format:
        $htmldoc->set_bodyfont('Times');
        $htmldoc->set_fontsize(10);
        $htmldoc->set_top_margin(10, 'mm');
        $htmldoc->set_left_margin(15, 'mm');
        $htmldoc->set_right_margin(15, 'mm');
        $htmldoc->set_bottom_margin(10, 'mm');
        
        # naughty, but setting not otherwise available:
        $self->_set_htmldoc_param('headfootsize', 9);
        # $htmldoc->set_footer('t', 'd', '1'); # doesn't work
    }

    if ( my $html = $args->{html} ) {
        # set session ID in case img called in tmpl (not passed by browser):
        if ( my $session = $args->{session} ) { # only gets passed if needed
            my $session_id = 'CGISESSID=' . $session->id;
            $self->_set_htmldoc_param(cookies => $session_id);  
        }
        $htmldoc->set_html_content($html);
    }
    elsif ( my $filename = $args->{file} ) { # warn $filename;
        $htmldoc->set_input_file('/tmp/'.$filename);
    }    
   
    my $pdf = $htmldoc->generate_pdf(); # my @errs =  $htmldoc->error(); warn @errs if @errs;

    return $pdf->to_string(); # $pdf->to_file('foo.pdf'); 
}

# wkhtmltopdf version; TODO: can't find static content (css, images, etc) in src file
# and does not call the image url - no request received for it in server logs
sub make_pdf_wkhtmltopdf {  # wkhtmltopdf needs symlink in /usr/bin/
    my ($self, $args) = @_;   

	my $filename = $args->{file};
    my $session  = $args->{session}; # only gets passed if needed
    my $session_id = 'CGISESSID=' . $session->id;
	
    my $pdf = `wkhtmltopdf --cookie $session_id $filename -`;
    return $pdf;
}

sub _build_htmldoc {
    my $self = shift;
    
    my $htmldoc = new HTML::HTMLDoc(mode => 'file', tmpdir =>'/tmp');
    return $htmldoc;
}

# need to use undocumented 'private' _set_doc_config method for unsupported params:
sub _set_htmldoc_param {
    my $self = shift;    
    
    $self->htmldoc->_set_doc_config(@_); # pass args straight in
}

1;