<?php
class PrintAnything
{
    var $_context = 0;

    function _prepareString($str)
    {
        $str = str_replace("\r", '', $str);
        $str = str_replace("\n", '\n', $str);
        $str = str_replace("\047", "\\'", $str);
        $str = str_replace('"', '\"', $str);
        return $str;
    }

    function readBody($fname)
    {
        $html = '';
        ob_start();
        if (@readfile($fname)) {
            $html = ob_get_contents();
        }
        ob_end_clean();
        if (preg_match('#<body[^>]*>(.+?)</body>#is', $html, $matches)) {
            $html = $matches[1];
        }
        return $html;
    }

    function addPrintContext($printHtml, $stylesheet = array())
    {
        $this->_context += 1;
        $printHtml = $this->_prepareString($printHtml);
       
	    echo '<!-- PRINTING CONTEXT ' . $this->_context . ' -->' . "\n";
        echo '<style type="text/css">' . "\n";
        echo '@media print {' . "\n";
        echo '    #PAScreenOut' . $this->_context . ' { display: none; }' . "\n";
        foreach ($stylesheet as $k => $v) {
            echo '    ' . $k . ' { ' . $v . '}' . "\n";
        }
        echo '}' . "\n";
        echo '@media screen {' . "\n";
        echo '    #PAPrintOut' . $this->_context . ' { display: none; }' . "\n";
        echo '}' . "\n";
        echo '</style>' . "\n";
        echo '<script type="text/javascript" language="JavaScript">' . "\n";
        echo 'function PA_GoPrint_' . $this->_context . '()' . "\n";
        echo '{' . "\n";
        echo '    document.body.innerHTML = \'<div id="PAScreenOut' . $this->_context . '">\' + document.body.innerHTML + \'<\/div>\';' . "\n";
        echo '    document.body.innerHTML += \'<div id="PAPrintOut' . $this->_context . '">' . $printHtml . '<\/div>\';' . "\n";
        echo '    window.print();' . "\n";
        echo '}' . "\n";
        echo '</script>' . "\n";
        echo '<!-- END OF PRINTING CONTEXT ' . $this->_context . ' -->' . "\n";
        return $this->_context;
    }

    function showPrintLink($context, $linkText, $attributes = '')
    {
        echo '<a href="javascript:PA_GoPrint_' . $context . '()"' . (!empty($attributes) ? ' ' . $attributes : '') . '>' . $linkText . '</a>';
    }

    function showPrintButton($context, $buttonText, $attributes = '')
    {
        echo '<input type="button" value="' . $buttonText . '"' . (!empty($attributes) ? ' ' . $attributes : '') . ' onclick="PA_GoPrint_' . $context . '()" />';
    }

}

?>