PHPology is a collective of highly skilled, award winning, web gurus.
Contact Raj on 07985 467 213 or email [email protected]

PHP Printer() function with custom font styling using CSS

I had a task for a potential project where I required PHP to print to a network printer.

Problem was that with the general PHP printer function I was struggling to

1. handle large amounts of text and
2. add styling (although using printer_draw_text() did help, but the text would not wordwrap).

Anyway, whilst searching the net, there was not much around on how to solve this problem so I came up with a way using HTML2PDF. Now I was able to prepare the text needed (adding my styling, etc), export it out as a PDF document and have that ready to print but using the windows command "print" (should work fine for *nix environment too).

Below is the outline of the code used (p.s. its not the cleanest)

<?php
$filename = 'html-template.html'; //basically contains the html code including the styling if nessesary which will be converted into the PDF
$pdf_filename = date("YmdHis").'.pdf';
$print_command = "print /D:NETWORK-NAMEPRINTER-NAME "".$_SERVER['DOCUMENT_ROOT'].$pdf_filename."""; //send print command to printer with the pdf document path to print

//load in the template to convert to PDF
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);

//load in the text you need here.
$comment = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries";

//replace the ##COMMENT## within the contents variable
$contents = str_replace("##COMMENT##", $comment, $contents);

// conversion HTML =--> PDF
require(PDFHTML_URL."html2pdf.class.php");
try
{
    $html2pdf = new HTML2PDF('L','A4','en', true, 'UTF-8', 'ISO-8859-15');
    $html2pdf->pdf->SetDisplayMode('fullpage');
    $html2pdf->writeHTML($contents);
    $html2pdf->Output($pdf_filename, 'f');
}
catch(HTML2PDF_exception $e)
{
    echo $e;
}

echo $contents; //debug

if($_GET['do'] == "print")
{
    system($print_command, $output);
    echo "

".$output."

"; echo "

".$print_command."

"; } exit; ?>

 

The contents within my html-template.html is (which follows the HTML2PDF example):

<page>
    <table>
        <tr>
            <td>
            <h1>##COMMENT##</h1>
            </td>
        </tr>
    </table>
</page>