Monday, 13 August 2018

Printing Directly From PHP

Some of you might be surprised that you can print directly to a printer of your choice through PHP. This uses a PECL extension but is only available on Windows. It is possible to print using UNIX systems, but you have to call the ps program using the system function.
To install the printer functions on Windows you need to download the PECL library for Windows, found at pecl4win.php.net. Unzip this file and move the file php_printer.dll to your extensions directory in your PHP dicrectory (usually called ext).
Next, open up your php.ini file and add the following line at the end of the extensions list.
extension=php_printer.dll
Then add the following lines at the bottom of the file. This tells PHP what printer to use as a default. If the printer is locally installed then PHP only needs the name.
  1. [printer]
  2. printer.default_printer = "Your printer name"
If the printer is installed on another computer then you need to supply the full address. This would look something like \\server\printer.
Save this and restart the web server. You should now have access to the printer functions. Make sure your printer is on, and that you have enough printer ink and you can get started.
To use these function to need to open the printer, start a document, and then start a page. You can have more than one page by ending and starting pages. Here is the basic model you will need to get started.
  1. // start printer
  2. $handle = printer_open();
  3. printer_start_doc($handle, "My Document");
  4. printer_start_page($handle);
  5. // create content here
  6. // print
  7. printer_end_page($handle);
  8. printer_end_doc($handle);
  9. printer_close($handle);
To create some content you need to call certain functions using the printer handle as a parameter. You can print text, lines, shapes and even images using a number of different functions. To print text you need to use the printer_draw_text() function, the first parameter is the printer handle, the second is the text to be printed and the last two are the x and y coordinates of the text on the page.
printer_draw_text($handle, 'the text that will be printed', 100, 100);
Of course, you will probably want to use a font to print with, in which case use the following additions to the code.
  1. $font = printer_create_font("Arial", 72, 48, 400, false, false, false, 0);
  2. printer_select_font($handle, $font);
  3. printer_draw_text($handle, 'the text that will be printed', 100, 100);
  4. printer_delete_font($font);
Drawing a line is nice and easy
  1. $pen = printer_create_pen(PRINTER_PEN_SOLID, 30, "123fde");
  2. printer_select_pen($handle, $pen);
  3.  
  4. printer_draw_line($handle, 1, 10, 1000, 10);
  5. // draw more lines if you want...
  6.  
  7. printer_delete_pen($pen);
These are just two examples, there are a number of other functions available on the PHP Printer page.

0 comments:

Post a Comment