Sample Perl CGI Script

In this chapter…

…we will discuss implementing a Perl CGI scripts.

This sample script is based on an FDFMerge sample script on the Appligent website. The algorithm of the script is discussed in FDFMerge – Automating or FDFMerge Lite – Automating.

#PERL cgi source for FDFMerge Mutual Fund Demonstration

####################################################################################
##Configuration section-replace paths with your own data if not using default.##
####################################################################################
## Webmasters E-mail address, replace with your own. Make sure 
## a \ is included before the @ and .
# Address appears on server error page if error occurs.
$webmaster = "webmaster\@appligent\.com";
$Platform = "WIN"; # WIN or Unix

# set up general paths and program locations
## Path to fdfmerge without extension
$FDFMergeRoot  = "C:/Appligent/FDFMerge/fdfmerge";

## Main Directory where files are located
$MainDir = "C:/Appligent/Demos/WebSiteExamples/FDFMerge_PerlDemo";

## Path/filename for FDFMerge to create output file. 
## ("output file" is the new copy of PDF returned by FDFMerge 
## with the merged/stamped data)
## If you do not want to include the time in the output file name, 
## remove the $tm.
## Prints as filename120101.pdf. (if time was 12:01:01)
$outputDirName = "output"; # name of folder to contain all output files
$outputDir = "$MainDir/$outputDirName"; #Full path to output files
$outfileName = "out_SimpleDemo.pdf"; # name for output pdf file
$outfile = "$outputDir/$outfileName"; # Path & name for output PDF file

$pdffile = "$MainDir/input/SimpleDemo.pdf"; #Path & name for input PDF form
$fdffile = "$outputDir/SimpleDemo.fdf"; #Path & name for fdf or xfdf file
$logfile = "$outputDir/logfile.txt"; #Path & name for log file for FDFMerge

# Remove Comment marks to print to Debug text file
#open(DEBUG,  ">" . "$outputDir/debug.txt")  || die "problem: $!";
#print DEBUG "Starting Log\n";

############################## End Configuration Section ########################
#################################################################################

### Start main section of script ###

# set up executable and reg number
$FDFMerge = $FDFMergeRoot . "app";

# Read the Data submitted from the server:
&parse_form_data (*simple_form);

# Read subbmitted data into variables and set merge option
$merge = ReadFormData();

# Write FDF file to disk.
&WriteFDF($fdffile);



# Run FDFMerge
$execute = "$FDFMerge -r $FDFMergeRegNum $merge -p -l $logfile 
  -o $outfile $pdffile $fdffile";
`$execute`;
#print DEBUG "$execute\n";

#start of html page with link to newly created file
$wpth = "$outputDirName/$outfileName ";
print "Location: $wpth\n\n";
print "Content-type: application/pdf\n";
print "<html>","\n";
print "<head>","\n";
print "<title>FDFMerge Demo PDF File</title>","\n";
print "</head>\n";
print "</html>";

##############################################################################

## If you need help setting up this demo or if you have any questions about
## FDFMerge, please contact our Technical support dept. by e-mail, 
## support@appligent.com
## or by phone, 610-284-4006

## Copyright©2002 Appligent, Inc. All rights reserved.
## Sample Code supplied as example, use at your own risk. 
## We have tried to make this example easy to read and use. 
## However, Appligent makes no guarantees of any kind that this 
## code will work on your system.

############################## Subroutines ##################################
#############################################################################
# Parse the submitted HTML form data or the PDF Form data submitted as HTML.
## Parse form
sub parse_form_data
{
    local (*FORM_DATA) = @_;
    local ( $request_method, $query_string, @key_value_pairs,
           $key_value, $key, $value);

    $request_method = $ENV{'REQUEST_METHOD'};
    if ($request_method eq "GET") {
        $query_string = $ENV{'QUERY_STRING'};
    } elsif ($request_method eq "POST") {
        read (STDIN, $query_string, $ENV{'CONTENT_LENGTH'});
    } else {
        &return_error (500, "Server Error",
                       "Server uses unsupported method");
    }

    @key_value_pairs = split (/&/, $query_string);

    foreach $key_value (@key_value_pairs) {
        ($key, $value) = split (/=/, $key_value);
        $value =~ tr/+/ /;
        $value =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg;

        if (defined($FORM_DATA{$key})) {
            $FORM_DATA{$key} = join ("", $FORM_DATA{$key}, $value);
        } else {
            $FORM_DATA{$key} = $value;
        }
    }
}

############################################################################
## Get data from parsed form to variables

sub ReadFormData{

$name = $simple_form{'name'};
$co = $simple_form{'company'};
$city = $simple_form{'city'};
$state = $simple_form{'state'};
$country = $simple_form{'country'};
$email = $simple_form{'email'};
$merge_option = $simple_form{'merge_option'};

if ($merge_option eq "merge") {
 $merge = "";
 } else {
 $merge = "-s";
 }
 
$ReadFormData = $merge;
}


############################################################################
## Create FDF File
sub WriteFDF {

$fdffile = $_[0];
open FILE, join ("",">",$fdffile);

#if above line fails with your version of perl try the line below.
#open (FILE, ">" . $fdffile);

print FILE<<EOT;
%FDF-1.2

1 0 obj
<< 
/FDF 
<< /Fields [ 
<< /V ($city)/T (city)>> 
<< /V ($co)/T (company)>> 
<< /V ($country)/T (country)>> 
<< /V ($email)/T (email)>> 
<< /V /$merge_option /T (merge_option)>> 
<< /V ($name)/T (name)>> 
<< /V ($state)/T (state)>> 
] 
>> 
>> 
endobj
trailer
<<
/Root 1 0 R 
>>
%%EOF
EOT

close FILE;
}

############################################################################
## Return Error
sub return_error
{
    local ($status, $keyword, $message) = @_;

    print "Content-type: text/html\n\n";
    print "Status: ", $status, " ", $keyword, "\n\n";

    print <<End_of_Error;

<title>CGI Program - Unexpected Error</title>
<h1>$keyword</h1>
<hr>$message</hr>
Please contact $webmaster for more information.

End_of_Error

    exit(1);
}