Search code examples
perlpdf-generationpdftk

PDF::Tk Background Image


I have a code that spits out a bunch of lines of HTML, turns into PSLines, with turns into PDF Lines. After the PDF lines I need PDF::Tk to insert a background image.

Below is my code, with a comment on where I think I need the code. Can anyone help me with this code snippet?

sub printFilePdf {
    my $unique_id = shift;
    my ($file) = "$OUTFILES/$id.html";

    open(my $htmlFH, '<', $file) or die "Can't open file $file $!\n";

    my $processId = open2(\*POUT, \*PIN, qq(html2ps -U -f /home/apache/cgi-bin/test/html2psrc-tst));

    my @lines = <$htmlFH>;
    print PIN @lines;
    close PIN;

    my @psLines;
    while (<POUT>) 
    {
        chomp;
        push(@psLines,$_);
    }
    waitpid $processId, 0;

    $processId = open2(\*POUT, \*PIN, qq(ps2pdf -sPAPERSIZE=letter - -));
    print PIN "$_\n" foreach(@psLines);
    close PIN;

    my @pdfLines;
    while (<POUT>) {
        chomp;
        push(@pdfLines, $_);
    }
    waitpid $processId, 0;

    #Insert Code Here

    print "Content-Type: application/pdf\n";
    print "Content-Disposition: attachment; filename=driverhistoryrecord.pdf\n\n";
    print "$_\n" foreach(@pdfLines);
    }

Solution

  • PDF::Tk is not exactly intuitive, call_pdftk($INPUT, $OUTPUT, @ARGS) executes pdftk $INPUT @ARGS output $OUTPUT... You can get help on what to feed to @ARGS from man pdftk.

    my $pdftk = PDF::Tk->new;
    $pdftk->call_pdftk(\$PDF_AS_STRING, \$OUT, 'background', 'bg.pdf');
    
    print "Content-Type: application/pdf\r\n";
    print "Content-Disposition: attachment; filename=done.pdf\r\n\r\n";
    print $OUT;
    

    Alternatively you might want to take a look at something like HTML::HTMLDoc which has support for <body background="bg.jpg"> and a set_bodyimage($image) function.

    use HTML::HTMLDoc;
    my $htmldoc = new HTML::HTMLDoc;
    $htmldoc->set_html_content(<<"EOF");
    <html><body>   
    This is my <b>pdf</b>...
    </body></html>
    EOF
    
    $htmldoc->set_bodyimage('bg.png');
    print $htmldoc->generate_pdf()->to_string();