# Chapter 5 - Using HTMLDOC on a Web Server

This chapter describes how to interface HTMLDOC to your web server using CGI and your own server-side scripts and programs.

## The Basics

HTMLDOC can be used in a variety of ways to generate formatted reports on a web server. The most common way is to use HTMLDOC as a CGI program with your web server to provide PDF-formatted output of a web page. Examples are provided for Microsoft IIS and the Apache web servers.

HTMLDOC can also be called from your own server-side scripts and programs. Examples are provided for PHP and Java.

WARNING: Passing information directly from the web browser to HTMLDOC can potentially expose your system to security risks. Always be sure to "sanitize" any input from the web browser so that filenames, URLs, and options passed to HTMLDOC are not acted on by the shell program or other processes.

## Using HTMLDOC as a CGI Program

HTMLDOC 1.8.24 and higher supports operation as a CGI program. You can copy or symlink the htmldoc (all but Windows) or htmldoc.exe (Windows) executable to your web server's cgi-bin directory and then use it to produce PDF versions of your web pages.

The CGI converts a page on your local server to PDF and sends it to the client's web browser. For example, to convert a page called superproducts.html at the following URL:

        http://servername/superproducts.html

and if you installed HTMLDOC in your server's cgi-bin directory, you would direct your clients to the following URL:

        http://servername/cgi-bin/htmldoc/superproducts.html

The boldface portion represents the location of the HTMLDOC executable on the web server. You simply place that path before the page you want to convert.

Form data using the `GET` method can be passed at the end of the URL, for example:

        http://servername/cgi-bin/htmldoc/superproducts.html?name=value

### Server-Side Preferences

When run as a CGI program, HTMLDOC will try to read a book file to set any preferences for the conversion to PDF. For the superproducts.html file described previously, HTMLDOC will look at the following URLs for a book file:

        http://servername/superproducts.html.book
        http://servername/.book
        http://servername/cgi-bin/.book

The first book file that is found will be used.

### Configuring HTMLDOC with Apache

The Apache web server is easily configured to use HTMLDOC. The simplest way is to copy or symlink the htmldoc executable to the configured cgi-bin directory. For example, if your Apache installation is configured to look for CGI programs in the /var/www/cgi-bin directory, the default for Apache on Red Hat Linux, then the command to install HTMLDOC on your web server would be:

        ln -s /usr/bin/htmldoc /var/www/cgi-bin ENTER

If you are using Apache 2.0.30 or higher, you will also need to enable `PATH_INFO` support by adding the following line to your httpd.conf file:

        AcceptPathInfo On

Apache also allows you to associate CGI programs with a specific extension. If you add the following line to your httpd.conf file:

        AddHandler cgi-script .cgi

and enable CGI execution with the `Options` directive for a directory:

        Options +ExecCGI

then you can copy or symlink the htmldoc executable to an alternate location. For example, if you have a web directory called /var/www/htdocs/products, you can install HTMLDOC in this directory with the following command:

        ln -s /usr/bin/htmldoc /var/www/htdocs/products/htmldoc.cgi ENTER

### Configuring HTMLDOC with Microsoft IIS

The IIS web server is configured to run CGI programs by either modifying the permissions of an existing directory or by creating a new virtual directory that allows for execution of programs. Start by running the Internet Services Manager program (Figure 5-1):

1. Click on Start
2. Click on Settings
3. Click on Control Panel
4. Double-click on Administrative Tools
5. Double-click on Internet Services Manager

After the Internet Services Manager window (Figure 5-1) appears, perform the following steps to add a virtual folder for HTMLDOC:

1. Click on your server in the list to show the default web site service in the list (Figure 5-2)
2. Choose New->Virtual Directory from the Action menu (Figure 5-3)
3. Click Next when the Virtual Directory Creation Wizard window appears (Figure 5-4)
4. Enter the name `htmldoc` in the Alias field and click Next (Figure 5-5)
5. Enter the HTMLDOC program folder in the Directory field and click Next (Figure 5-6)
6. Check the Execute (such as ISAPI applications or CGI) box and click Next (Figure 5-7)
7. Click Finish to dismiss the wizard (Figure 5-8)

If you are using IIS 6.0, proceed to the next section titled, "Additional Configuration for IIS 6.0".

Figure 5-1: The Internet Services Manager Window

Figure 5-2: The Default Web Site Service

Figure 5-3: Adding a New Virtual Directory

Figure 5-4: The Virtual Directory Creation Wizard Window

Figure 5-5: Entering the Alias Name

Figure 5-6: Entering the HTMLDOC Program Folder

Figure 5-7: Enabling CGI Mode

Figure 5-8: Completion of IIS Configuration

Once configured, the htmldoc.exe program will be available in the web server directory. For example, for a virtual directory called cgi-bin, the PDF converted URL for the superproducts.html page would be as follows:

        http://servername/cgi-bin/htmldoc.exe/superproducts.html

The boldface portion represents the location of the HTMLDOC program on the web server.

### Additional Configuration for IIS 6.0

IIS 6.0 requires additional configuration steps due to its increased focus on security. Start by running the Internet Services Manager program (Figure 5-1):

1. Click on Start
2. Click on Settings
3. Click on Control Panel
4. Double-click on Administrative Tools
5. Double-click on Internet Services Manager

After the Internet Services Manager window (Figure 5-1) appears, perform the following steps to add a new Wed Service Extension for HTMLDOC:

1. Click on Web Service Extensions
2. Click Add a new Web Service Extension
3. Enter the name "HTMLDOC" when the Web Service Extension window appears
4. Click Add... and choose the htmldoc.exe file from the program folder, typically C:\Program Files\Easy Software Products\HTMLDOC
5. Check the Set extension status to Allowed box
6. Click OK to add the extension and dismiss the window

Finally, double-click the My Computer icon on the desktop or start the Windows Explorer. When the explorer window appears, perform the following steps to provide write access to the Windows temporary folder:

1. Open the windows temporary file folder, typically C:\WINDOWS\TEMP
2. Choose Properties from the File menu
3. Click on the Security tab
4. Click Add..., enter the username for the web server, typically "SERVER\IUSR_SERVER" where "SERVER" is the name you gave your server, and click OK
5. Click on the username you just added in the list
6. Check the Read and Write permissions
7. Click OK to save the changes

## Using HTMLDOC From Server-Side Scripts and Programs

To make this work the CGI script or program must send the appropriate HTTP attributes, the required empty line to signify the beginning of the document, and then execute the HTMLDOC program to generate the HTML, PostScript, or PDF file as needed. Since HTMLDOC looks for CGI environment variables when it is run, you must also set the `HTMLDOC_NOCGI` environment variable to a value of 1 before running HTMLDOC from your CGI script or program.

Another way to generate PDF files from your reports is to use HTMLDOC as a "portal" application. When used as a portal, HTMLDOC automatically retrieves the named document or report from your server and passes a PDF version to the web browser. See the next sections for more information.

### Calling HTMLDOC from a Shell Script

Shell scripts are probably the easiest to work with, but are normally limited to GET type requests. Here is a script called topdf that acts as a portal, converting the named file to PDF:

        #!/bin/sh
        #
        # Sample "portal" script to convert the named HTML file to PDF on-the-fly.
        #
        # Usage: http://www.domain.com/path/topdf/path/filename.html
        #

        #
        # Tell HTMLDOC not to run in CGI mode...
        #

        HTMLDOC_NOCGI=1; export HTMLDOC_NOCGI

        #
        # The "options" variable contains any options you want to pass to HTMLDOC.
        #

        options='-t pdf --webpage --header ... --footer ..."

        #
        # Tell the browser to expect a PDF file...
        #

        echo "Content-Type: application/pdf"
        echo ""

        #
        # Run HTMLDOC to generate the PDF file...
        #

        htmldoc $options http://${SERVER_NAME}:${SERVER_PORT}$PATH_INFO

Users of this CGI would reference the URL "http://www.domain.com/topdf.cgi/index.html" to generate a PDF file of the site's home page.

The options variable in the script can be set to use any supported command-line option for HTMLDOC; for a complete list see Chapter 8 - Command-Line Reference.

### Calling HTMLDOC from Perl

Perl scripts offer the ability to generate more complex reports, pull data from databases, etc. The easiest way to interface Perl scripts with HTMLDOC is to write a report to a temporary file and then execute HTMLDOC to generate the PDF file.

Here is a simple Perl subroutine that can be used to write a PDF report to the HTTP client:

        sub topdf {
    	# Get the filename argument...
    	my $filename = shift;

    	# Make stdout unbuffered...
    	select(STDOUT); $| = 1;

    	# Tell HTMLDOC not to run in CGI mode...
            $ENV{HTMLDOC_NOCGI} = 1;

    	# Write the content type to the client...
    	print "Content-Type: application/pdf\n\n";

    	# Run HTMLDOC to provide the PDF file to the user...
    	system "htmldoc -t pdf --quiet --webpage $filename";
        }

### Calling HTMLDOC from PHP

PHP is quickly becoming the most popular server-side scripting language available. PHP provides a `passthru()` function that can be used to run HTMLDOC. This combined with the `header()` function can be used to provide on-the-fly reports in PDF format.

Here is a simple PHP function that can be used to convert a HTML report to PDF and send it to the HTTP client:

        function topdf($filename, $options = "") {
    	# Tell HTMLDOC not to run in CGI mode...
            putenv("HTMLDOC_NOCGI=1");

    	# Write the content type to the client...
    	header("Content-Type: application/pdf");
    	flush();

    	# Run HTMLDOC to provide the PDF file to the user...
    	passthru("htmldoc -t pdf --quiet --jpeg --webpage $options '$filename'");
        }

The function accepts a filename and an optional "options" string for specifying the header, footer, fonts, etc.

To prevent malicious users from passing in unauthorized characters into this function, the following function can be used to verify that the URL/filename does not contain any characters that might be interpreted by the shell:

        function bad_url($url) {
    	// See if the URL starts with http: or https:...
    	if (strncmp($url, "http://", 7) != 0 &&
    	    strncmp($url, "https://", 8) != 0) {
                return 1;
    	}

    	// Check for bad characters in the URL...
    	$len = strlen($url);
    	for ($i = 0; $i < $len; $i ++) {
                if (!strchr("~_*()/:%?+-&@;=,$.", $url[$i]) &&
    		!ctype_alnum($url[$i])) {
    		return 1;
    	    }
    	}

    	return 0;
        }

Another method is to use the `escapeshellarg()` function provided with PHP 4.0.3 and higher to generate a quoted shell argument for HTMLDOC.

To make a "portal" script, add the following code to complete the example:

        global $SERVER_NAME;
        global $SERVER_PORT;
        global $PATH_INFO;
        global $QUERY_STRING;

        if ($QUERY_STRING != "") {
    	$url = "http://${SERVER_NAME}:${SERVER_PORT}${PATH_INFO}?${QUERY_STRING}";
        } else {
    	$url = "http://${SERVER_NAME}:${SERVER_PORT}$PATH_INFO";
        }

        if (bad_url($url)) {
          print("<html><head><title>Bad URL</title></head>\n"
    	   ."<body><h1>Bad URL</h1>\n"
    	   ."<p>The URL <b><tt>$url</tt></b> is bad.</p>\n"
    	   ."</body></html>\n");
        } else {
          topdf($url);
        }

### Calling HTMLDOC from C

C programs offer the best flexibility and easily supports on-the-fly report generation without the need for temporary files.

Here are some simple C functions that can be used to generate a PDF report to the HTTP client from a temporary file or pipe:

        #include <stdio.h>
        #include <stdlib.h>

        /* topdf() - convert a HTML file to PDF */
        FILE *topdf(const char *filename)           /* I - HTML file to convert */
        {
          char	command[1024];			/* Command to execute */

         /*
          * Tell HTMLDOC not to run in CGI mode...
          */

          putenv("HTMLDOC_NOCGI=1");

         /*
          * Write the content type to the client...
          */

          puts("Content-Type: application/pdf\n");

         /*
          * Run HTMLDOC to provide the PDF file to the user...
          */

          sprintf(command, "htmldoc --quiet -t pdf --webpage %s", filename);

          return (popen(command, "w"));
        }

        /* topdf2() - pipe HTML output to HTMLDOC for conversion to PDF */
        FILE *topdf2(void)
        {
         /*
          * Tell HTMLDOC not to run in CGI mode...
          */

          putenv("HTMLDOC_NOCGI=1");

         /*
          * Write the content type to the client...
          */

          puts("Content-Type: application/pdf\n");

         /*
          * Open a pipe to HTMLDOC...
          */

          return (popen("htmldoc --quiet -t pdf --webpage -", "w"));
        }

### Calling HTMLDOC from Java

Java programs are a portable way to add PDF support to your web server. Here is a class called htmldoc that acts as a portal, converting the named file to PDF. It can also be called by your Java servlets to process an HTML file and send the result to the client in PDF format:

        class htmldoc
        {
          // Convert named file to PDF on stdout...
          public static int topdf(String filename)// I - Name of file to convert
          {
            String              command;          // Command string
            Process             process;          // Process for HTMLDOC
            Runtime             runtime;          // Local runtime object
            java.io.InputStream input;            // Output from HTMLDOC
            byte                buffer [];        // Buffer for output data
            int                 bytes;            // Number of bytes

            // First tell the client that we will be sending PDF...
            System.out.print("Content-type: application/pdf\n\n");

            // Construct the command string
            command = "htmldoc --quiet --jpeg --webpage -t pdf --left 36 " +
                      "--header .t. --footer .1. " + filename;

            // Run the process and wait for it to complete...
            runtime = Runtime.getRuntime();

            try
            {
              // Create a new HTMLDOC process...
              process = runtime.exec(command);

              // Get stdout from the process and a buffer for the data...
              input  = process.getInputStream();
              buffer = new byte[8192];

              // Read output from HTMLDOC until we have it all...
              while ((bytes = input.read(buffer)) > 0)
                System.out.write(buffer, 0, bytes);

              // Return the exit status from HTMLDOC...
              return (process.waitFor());
            }
            catch (Exception e)
            {
              // An error occurred - send it to stderr for the web server...
              System.err.print(e.toString() + " caught while running:\n\n");
              System.err.print("    " + command + "\n");
              return (1);
            }
          }

          // Main entry for htmldoc class
          public static void main(String[] args)// I - Command-line args
          {
            String server_name,                 // SERVER_NAME env var
                   server_port,                 // SERVER_PORT env var
                   path_info,                   // PATH_INFO env var
                   query_string,                // QUERY_STRING env var
                   filename;                    // File to convert

            if ((server_name = System.getProperty("SERVER_NAME")) != null &&
                (server_port = System.getProperty("SERVER_PORT")) != null &&
                (path_info = System.getProperty("PATH_INFO")) != null)
            {
              // Construct a URL for the resource specified...
              filename = "http://" + server_name + ":" + server_port + path_info;

              if ((query_string = System.getProperty("QUERY_STRING")) != null)
              {
                filename = filename + "?" + query_string;
              }
            }
            else if (args.length == 1)
            {
              // Pull the filename from the command-line...
              filename = args[0];
            }
            else
            {
              // Error - no args or env variables!
              System.err.print("Usage: htmldoc.class filename\n");
              return;
            }

            // Convert the file to PDF and send to the web client...
            topdf(filename);
          }
        }