Copyright (c) 2014-2015 Michael Billington , incorporating modifications by: - Roni Saha - Gergely Radics - Warren Doyle Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This class generates ESC/POS printer control commands for compatible printers. See README.md for a summary of compatible printers and supported commands, and basic usage. See example/demo.php for a detailed print-out demonstrating the range of commands implemented in this project. Note that some functions have not been implemented: - Set paper sensors - Select print colour Please direct feature requests, bug reports and contributions to escpos-php on Github: - https://github.com/mike42/escpos-php
Example #1
2
function title(Printer $printer, $text)
{
    $printer->selectPrintMode(Printer::MODE_EMPHASIZED);
    $printer->text("\n" . $text);
    $printer->selectPrintMode();
    // Reset
}
 function testText()
 {
     /* Smoke test over text rendering with each profile.
      * Just makes sure we can attempt to print 'hello world' and a non-ASCII
      * char without anything blowing up */
     foreach ($this->checklist as $obj) {
         $connector = new DummyPrintConnector();
         $printer = new Printer($connector, $obj);
         $printer->text("Hello world €\n");
         $printer->close();
         // Check for character cache
         $profileName = $obj->getId();
         $expected = "Characters-{$profileName}.ser.z";
         $filename = __DIR__ . "/../../src/Mike42/Escpos/PrintBuffers/cache/{$expected}";
         $this->assertFileExists($filename);
     }
 }
Example #3
2
<?php

/* Example print-outs using the older bit image print command */
require __DIR__ . '/../autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\EscposImage;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
$connector = new FilePrintConnector("php://stdout");
$printer = new Printer($connector);
try {
    $tux = EscposImage::load("resources/tux.png", false);
    $printer->text("These example images are printed with the older\nbit image print command. You should only use\n\$p -> bitImage() if \$p -> graphics() does not\nwork on your printer.\n\n");
    $printer->bitImage($tux);
    $printer->text("Regular Tux (bit image).\n");
    $printer->feed();
    $printer->bitImage($tux, Printer::IMG_DOUBLE_WIDTH);
    $printer->text("Wide Tux (bit image).\n");
    $printer->feed();
    $printer->bitImage($tux, Printer::IMG_DOUBLE_HEIGHT);
    $printer->text("Tall Tux (bit image).\n");
    $printer->feed();
    $printer->bitImage($tux, Printer::IMG_DOUBLE_WIDTH | Printer::IMG_DOUBLE_HEIGHT);
    $printer->text("Large Tux in correct proportion (bit image).\n");
} catch (Exception $e) {
    /* Images not supported on your PHP, or image file not found */
    $printer->text($e->getMessage() . "\n");
}
$printer->cut();
$printer->close();
 page, you can set up a CapabilityProfile which either references its
 iconv encoding name, or includes all of the available characters.

 Here, we make use of CP858 for its inclusion of currency symbols which
 are not available in CP437. CP858 has good printer support, but is not
 included in all iconv builds.
*/
class CustomCapabilityProfile extends SimpleCapabilityProfile
{
    function getCustomCodePages()
    {
        /*
         * Example to print in a specific, user-defined character set
         * on a printer which has been configured to use i
         */
        return array('CP858' => "ÇüéâäàåçêëèïîìÄÅ" . "ÉæÆôöòûùÿÖÜø£Ø׃" . "áíóúñѪº¿®¬½¼¡«»" . "░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐" . "└┴┬├─┼ãÃ╚╔╩╦╠═╬¤" . "ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀" . "ÓßÔÒõÕµþÞÚÛÙýݯ´" . " ±‗¾¶§÷¸°¨·¹³²■ ");
    }
    function getSupportedCodePages()
    {
        return array(0 => 'custom:CP858');
    }
}
$connector = new FilePrintConnector("php://stdout");
$profile = CustomCapabilityProfile::getInstance();
$printer = new Printer($connector, $profile);
$printer->text("€ 9,95\n");
$printer->text("£ 9.95\n");
$printer->text("\$ 9.95\n");
$printer->text("¥ 9.95\n");
$printer->cut();
$printer->close();
Example #5
2
<?php

/*
 * This is an example of printing chinese text. This is a bit different to other character encodings, because
 * the printer accepts a 2-byte character encoding (GBK), and formatting is handled differently while in this mode.
 *
 * At the time of writing, this is implemented separately as a textChinese() function, until chinese text
 * can be properly detected and printed alongside other encodings.
 */
require __DIR__ . '/../../autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
use Mike42\Escpos\CapabilityProfiles\SimpleCapabilityProfile;
$connector = new FilePrintConnector("/dev/usb/lp1");
$profile = SimpleCapabilityProfile::getInstance();
$printer = new Printer($connector);
// Example text from #37
$printer->textChinese("艾德蒙 AOC E2450SWH 23.6吋 LED液晶寬螢幕特價\$ 19900\n\n");
// Note that on the printer tested (ZJ5890), the font only contained simplified characters.
$printer->textChinese("示例文本打印机!\n\n");
$printer->close();
<?php

/*
 * Example of printing Spanish text on SEYPOS PRP-300 thermal line printer.
 * The characters in Spanish are available in code page 437, so no special
 * code pages are needed in this case (SimpleCapabilityProfile).
 *
 * Use the hardware switch to activate "Two-byte Character Code"
 */
require __DIR__ . '/../../autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
use Mike42\Escpos\CapabilityProfiles\SimpleCapabilityProfile;
$connector = new FilePrintConnector("php://output");
$profile = SimpleCapabilityProfile::getInstance();
$printer = new Printer($connector);
$printer->text("El pingüino Wenceslao hizo kilómetros bajo exhaustiva lluvia y frío, añoraba a su querido cachorro.\n");
$printer->cut();
$printer->close();
Example #7
1
function title(Printer $printer, $str)
{
    $printer->selectPrintMode(Printer::MODE_DOUBLE_HEIGHT | Printer::MODE_DOUBLE_WIDTH);
    $printer->text($str);
    $printer->selectPrintMode();
}
Example #8
1
<?php

/* Example of Greek text on the P-822D */
require __DIR__ . '/../../autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\CapabilityProfiles\P822DCapabilityProfile;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
// Setup the printer
$connector = new FilePrintConnector("php://stdout");
$profile = P822DCapabilityProfile::getInstance();
$printer = new Printer($connector, $profile);
// Print a Greek pangram
$text = "Ξεσκεπάζω την ψυχοφθόρα βδελυγμία";
$printer->text($text . "\n");
$printer->cut();
// Close the connection
$printer->close();
<?php

require __DIR__ . '/../../autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
use Mike42\Escpos\CapabilityProfiles\StarCapabilityProfile;
use Mike42\Escpos\PrintBuffers\ImagePrintBuffer;
/* This example shows the printing of Latvian text on the Star TUP 592 printer */
$profile = StarCapabilityProfile::getInstance();
/* Option 1: Native character encoding */
$connector = new FilePrintConnector("php://stdout");
$printer = new Printer($connector, $profile);
$printer->text("Glāžšķūņa rūķīši dzērumā čiepj Baha koncertflīģeļu vākus\n");
$printer->cut();
$printer->close();
/* Option 2: Image-based output (formatting not available using this output) */
$buffer = new ImagePrintBuffer();
$connector = new FilePrintConnector("php://stdout");
$printer = new Printer($connector, $profile);
$printer->setPrintBuffer($buffer);
$printer->text("Glāžšķūņa rūķīši dzērumā čiepj Baha koncertflīģeļu vākus\n");
$printer->cut();
$printer->close();
<?php

require __DIR__ . '/../../autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
use Mike42\Escpos\CapabilityProfiles\DefaultCapabilityProfile;
$connector = new FilePrintConnector("php://stdout");
$profile = DefaultCapabilityProfile::getInstance();
$printer = new Printer($connector, $profile);
$printer->text("Μιχάλης Νίκος\n");
$printer->cut();
$printer->close();
Example #11
1
<?php

/* Change to the correct path if you copy this example! */
require __DIR__ . '/../../autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\CupsPrintConnector;
try {
    $connector = new CupsPrintConnector("EPSON_TM-T20");
    /* Print a "Hello world" receipt" */
    $printer = new Printer($connector);
    $printer->text("Hello World!\n");
    $printer->cut();
    /* Close printer */
    $printer->close();
} catch (Exception $e) {
    echo "Couldn't print to this printer: " . $e->getMessage() . "\n";
}
Example #12
1
<?php

/* Print-outs using the newer graphics print command */
require __DIR__ . '/../autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\EscposImage;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
$connector = new FilePrintConnector("php://stdout");
$printer = new Printer($connector);
try {
    $tux = EscposImage::load("resources/tux.png", false);
    $printer->graphics($tux);
    $printer->text("Regular Tux.\n");
    $printer->feed();
    $printer->graphics($tux, Printer::IMG_DOUBLE_WIDTH);
    $printer->text("Wide Tux.\n");
    $printer->feed();
    $printer->graphics($tux, Printer::IMG_DOUBLE_HEIGHT);
    $printer->text("Tall Tux.\n");
    $printer->feed();
    $printer->graphics($tux, Printer::IMG_DOUBLE_WIDTH | Printer::IMG_DOUBLE_HEIGHT);
    $printer->text("Large Tux in correct proportion.\n");
    $printer->cut();
} catch (Exception $e) {
    /* Images not supported on your PHP, or image file not found */
    $printer->text($e->getMessage() . "\n");
}
$printer->close();
Example #13
1
foreach ($pages as $page) {
    $printer->graphics($page, Printer::IMG_DOUBLE_HEIGHT | Printer::IMG_DOUBLE_WIDTH);
}
$printer->cut();
$printer->close();
/*
 * 3: PDF printing still too slow? If you regularly print the same files, serialize & compress your
 * EscposImage objects (after printing[1]), instead of throwing them away.
 * 
 * (You can also do this to print logos on computers which don't have an
 * image processing library, by preparing a serialized version of your logo on your PC)
 * 
 * [1]After printing, the pixels are loaded and formatted for the print command you used, so even a raspberry pi can print complex PDF's quickly.
 */
$connector = new FilePrintConnector("php://stdout");
$printer = new Printer($connector);
$pdf = 'resources/document.pdf';
$ser = 'resources/document.z';
if (!file_exists($ser)) {
    $pages = ImagickEscposImage::loadPdf($pdf);
} else {
    $pages = unserialize(gzuncompress(file_get_contents($ser)));
}
foreach ($pages as $page) {
    $printer->graphics($page);
}
$printer->cut();
$printer->close();
if (!file_exists($ser)) {
    file_put_contents($ser, gzcompress(serialize($pages)));
}
Example #14
1
<?php

/*
 * Example of two-color printing, tested on an epson TM-U220 with two-color ribbon installed.
 */
require __DIR__ . '/../../autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
$connector = new FilePrintConnector("/dev/usb/lp0");
$printer = new Printer($connector);
try {
    $printer->text("Hello World!\n");
    $printer->setColor(Escpos::COLOR_2);
    $printer->text("Red?!\n");
    $printer->setColor(Escpos::COLOR_1);
    $printer->text("Default color again?!\n");
    $printer->cut();
} finally {
    /* Always close the printer! */
    $printer->close();
}
Example #15
1
<?php

require __DIR__ . '/../autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\EscposImage;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
$connector = new FilePrintConnector("php://stdout");
// Add connector for your printer here.
$printer = new Printer($connector);
/*
 * Due to its complxity, escpos-php does not support HTML input. To print HTML,
 * either convert it to calls on the Printer() object, or rasterise the page with
 * wkhtmltopdf, an external package which is designed to handle HTML efficiently.
 *
 * This example is provided to get you started: On Debian, first run-
 * 
 * sudo apt-get install wkhtmltopdf xvfb
 *
 * Note: Depending on the height of your pages, it is suggested that you chop it
 * into smaller sections, as printers simply don't have the buffer capacity for
 * very large images.
 *
 * As always, you can trade off quality for capacity by halving the width
 * (550 -> 225 below) and printing w/ Escpos::IMG_DOUBLE_WIDTH | Escpos::IMG_DOUBLE_HEIGHT
 */
try {
    /* Set up command */
    $source = __DIR__ . "/resources/document.html";
    $width = 550;
    $dest = tempnam(sys_get_temp_dir(), 'escpos') . ".png";
    $command = sprintf("xvfb-run wkhtmltoimage -n -q --width %s %s %s", escapeshellarg($width), escapeshellarg($source), escapeshellarg($dest));
 * The use case here is an Epson TM-T20II and German text.
 * 
 * Background: Not all ESC/POS features are available in the driver, so sometimes
 * you might want to send a custom commnad. This is useful for testing
 * new features.
 * 
 * The Escpos::text() function removes non-printable characters as a precaution,
 * so that commands cannot be injected into user input. To send raw data to
 * the printer, you need to write bytes to the underlying PrintConnector.
 * 
 * If you get a new command working, please file an issue on GitHub with a code
 * snippet so that it can be incorporated into escpos-php.
 */
/* Set up profile & connector */
$connector = new FilePrintConnector("php://output");
$profile = DefaultCapabilityProfile::getInstance();
// Works for Epson printers
$printer = new Printer($connector, $profile);
$cmd = Printer::ESC . "V" . chr(1);
// Try out 90-degree rotation.
$printer->getPrintConnector()->write($cmd);
$printer->text("Beispieltext in Deutsch\n");
$printer->cut();
$printer->close();
/*
 * Hex-dump of output confirms that ESC V 1 being sent:
 *
 * 0000000 033   @ 033   V 001   B   e   i   s   p   i   e   l   t   e   x
 * 0000010   t       i   n       D   e   u   t   s   c   h  \n 035   V   A
 * 0000020 003
 */
Example #17
0
<?php

/* Left margin & page width demo. */
require __DIR__ . '/../autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
$connector = new FilePrintConnector("php://stdout");
// Add connector for your printer here.
$printer = new Printer($connector);
/* Line spacing */
/*
$printer -> setEmphasis(true);
$printer -> text("Line spacing\n");
$printer -> setEmphasis(false);
foreach(array(16, 32, 64, 128, 255) as $spacing) {
    $printer -> setLineSpacing($spacing);
    $printer -> text("Spacing $spacing: The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.\n");
}
$printer -> setLineSpacing(); // Back to default
*/
/* Stuff around with left margin */
$printer->setEmphasis(true);
$printer->text("Left margin\n");
$printer->setEmphasis(false);
$printer->text("Default left\n");
foreach (array(1, 2, 4, 8, 16, 32, 64, 128, 256, 512) as $margin) {
    $printer->setPrintLeftMargin($margin);
    $printer->text("left margin {$margin}\n");
}
/* Reset left */
$printer->setPrintLeftMargin(0);
Example #18
0
<?php

require __DIR__ . '/printer/autoload.php';
require __DIR__ . '/require/db.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\EscposImage;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
/* Fill in your own connector here */
$connector = new FilePrintConnector("php://stdout");
/* Start the printer */
$printer = new Printer($connector);
/* Open file to write the ID */
$file = fopen("receipts/id.txt", "r") or die("asdsd");
$id = fgets($file);
fclose($file);
// Select customer and order info
$sql_orders = "select Order_id,o.cus_id,firstname as fname,lastname as lname,Date,Time,payed from orders as o LEFT JOIN customer_info as c ON o.cus_id = c.cus_id WHERE Order_id = {$id}";
$result = $mysql->query($sql_orders);
$row_order = $mysql->fetch($result);
if (empty($row_order['lname']) && empty($row_order['fname'])) {
    $cusname = 'Unknown';
} else {
    $cusname = $row_order['fname'] . " " . $row_order['lname'];
}
/* Print customer and order ID */
$printer->setJustification(Printer::JUSTIFY_CENTER);
$printer->selectPrintMode(Printer::MODE_DOUBLE_WIDTH);
$printer->text("{$cusname}\n");
$printer->selectPrintMode();
$printer->text("Order# {$id}\n");
$printer->feed(2);
Example #19
0
 /**
  * Convert widths and heights to characters. Used before sending graphics to set the size.
  *
  * @param array $inputs
  * @param boolean $long True to use 4 bytes, false to use 2
  * @return string
  */
 private static function dataHeader(array $inputs, $long = true)
 {
     $outp = array();
     foreach ($inputs as $input) {
         if ($long) {
             $outp[] = Printer::intLowHigh($input, 2);
         } else {
             self::validateInteger($input, 0, 255, __FUNCTION__);
             $outp[] = chr($input);
         }
     }
     return implode("", $outp);
 }
Example #20
0
 *      code pages ('character code tables') for your printer.
 *
 * The DefaultCapabilityProfile works for Espson-branded printers. For other models, you
 * must use/create a PrinterCapabilityProfile for your printer containing a list of code
 * page numbers for your printer- otherwise you will get mojibake.
 *
 * If you do not intend to use non-English characters, then use SimpleCapabilityProfile,
 * which has only the default encoding, effectively disabling code page changes.
 */
include dirname(__FILE__) . '/resources/character-encoding-test-strings.inc';
try {
    // Enter connector and capability profile (to match your printer)
    $connector = new FilePrintConnector("php://stdout");
    $profile = DefaultCapabilityProfile::getInstance();
    /* Print a series of receipts containing i18n example strings */
    $printer = new Printer($connector, $profile);
    $printer->selectPrintMode(Printer::MODE_DOUBLE_HEIGHT | Printer::MODE_EMPHASIZED | Printer::MODE_DOUBLE_WIDTH);
    $printer->text("Implemented languages\n");
    $printer->selectPrintMode();
    foreach ($inputsOk as $label => $str) {
        $printer->setEmphasis(true);
        $printer->text($label . ":\n");
        $printer->setEmphasis(false);
        $printer->text($str);
    }
    $printer->feed();
    $printer->selectPrintMode(Printer::MODE_DOUBLE_HEIGHT | Printer::MODE_EMPHASIZED | Printer::MODE_DOUBLE_WIDTH);
    $printer->text("Works in progress\n");
    $printer->selectPrintMode();
    foreach ($inputsNotOk as $label => $str) {
        $printer->setEmphasis(true);
 * The Ar-PHP library uses the default internal encoding, and can print
 * a lot of errors depending on the input, so be prepared to debug
 * the next four lines.
 * 
 * Note that this output shows that numerals are converted to placeholder
 * characters, indicating that western numerals (123) have to be used instead.
 */
mb_internal_encoding("UTF-8");
$Arabic = new I18N_Arabic('Glyphs');
$textLtr = $Arabic->utf8Glyphs($textUtf8, $maxChars);
$textLine = explode("\n", $textLtr);
/*
 * Set up and use an image print buffer with a suitable font
 */
$buffer = new ImagePrintBuffer();
$buffer->setFont($fontPath);
$buffer->setFontSize($fontSize);
$profile = EposTepCapabilityProfile::getInstance();
$connector = new FilePrintConnector("php://output");
// = new WindowsPrintConnector("LPT2");
// Windows LPT2 was used in the bug tracker
$printer = new Printer($connector, $profile);
$printer->setPrintBuffer($buffer);
$printer->setJustification(Printer::JUSTIFY_RIGHT);
foreach ($textLine as $text) {
    // Print each line separately. We need to do this since Imagick thinks
    // text is left-to-right
    $printer->text($text . "\n");
}
$printer->cut();
$printer->close();
Example #22
0
<?php

require __DIR__ . '/../autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
$connector = new FilePrintConnector("php://stdout");
$printer = new Printer($connector);
/* Height and width */
$printer->selectPrintMode(Printer::MODE_DOUBLE_HEIGHT | Printer::MODE_DOUBLE_WIDTH);
$printer->text("Height and bar width\n");
$printer->selectPrintMode();
$heights = array(1, 2, 4, 8, 16, 32);
$widths = array(1, 2, 3, 4, 5, 6, 7, 8);
$printer->text("Default look\n");
$printer->barcode("ABC", Printer::BARCODE_CODE39);
foreach ($heights as $height) {
    $printer->text("\nHeight {$height}\n");
    $printer->setBarcodeHeight($height);
    $printer->barcode("ABC", Printer::BARCODE_CODE39);
}
foreach ($widths as $width) {
    $printer->text("\nWidth {$width}\n");
    $printer->setBarcodeWidth($width);
    $printer->barcode("ABC", Printer::BARCODE_CODE39);
}
$printer->feed();
// Set to something sensible for the rest of the examples
$printer->setBarcodeHeight(40);
$printer->setBarcodeWidth(2);
/* Text position */
$printer->selectPrintMode(Printer::MODE_DOUBLE_HEIGHT | Printer::MODE_DOUBLE_WIDTH);
Example #23
0
use Mike42\Escpos\Printer;
use Mike42\Escpos\EscposImage;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
/* Fill in your own connector here */
$connector = new FilePrintConnector("php://stdout");
/* Information for the receipt */
$items = array(new item("Example item #1", "4.00"), new item("Another thing", "3.50"), new item("Something else", "1.00"), new item("A final item", "4.45"));
$subtotal = new item('Subtotal', '12.95');
$tax = new item('A local tax', '1.30');
$total = new item('Total', '14.25', true);
/* Date is kept the same for testing */
// $date = date('l jS \of F Y h:i:s A');
$date = "Monday 6th of April 2015 02:56:25 PM";
/* Start the printer */
$logo = EscposImage::load("resources/escpos-php.png", false);
$printer = new Printer($connector);
/* Print top logo */
$printer->setJustification(Printer::JUSTIFY_CENTER);
$printer->graphics($logo);
/* Name of shop */
$printer->selectPrintMode(Printer::MODE_DOUBLE_WIDTH);
$printer->text("ExampleMart Ltd.\n");
$printer->selectPrintMode();
$printer->text("Shop No. 42.\n");
$printer->feed();
/* Title of receipt */
$printer->setEmphasis(true);
$printer->text("SALES INVOICE\n");
$printer->setEmphasis(false);
/* Items */
$printer->setJustification(Printer::JUSTIFY_LEFT);
Example #24
0
/**
 * This is a demo script for the functions of the PHP ESC/POS print driver,
 * Escpos.php.
 *
 * Most printers implement only a subset of the functionality of the driver, so
 * will not render this output correctly in all cases.
 *
 * @author Michael Billington <*****@*****.**>
 */
require __DIR__ . '/../autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
use Mike42\Escpos\EscposImage;
$connector = new FilePrintConnector("php://stdout");
$printer = new Printer($connector);
/* Initialize */
$printer->initialize();
/* Text */
$printer->text("Hello world\n");
$printer->cut();
/* Line feeds */
$printer->text("ABC");
$printer->feed(7);
$printer->text("DEF");
$printer->feedReverse(3);
$printer->text("GHI");
$printer->feed();
$printer->cut();
/* Font modes */
$modes = array(Printer::MODE_FONT_B, Printer::MODE_EMPHASIZED, Printer::MODE_DOUBLE_HEIGHT, Printer::MODE_DOUBLE_WIDTH, Printer::MODE_UNDERLINE);
Example #25
0
 /**
  * Write data to the underlying printer.
  *
  * @param string $data
  */
 private function write($data)
 {
     $this->printer->getPrintConnector()->write($data);
 }
Example #26
0
$tmpf_path = tempnam(sys_get_temp_dir(), 'escpos-php');
$imgCombined_path = $tmpf_path . ".png";
try {
    // Convert, load image, remove temp files
    $cmd = sprintf("convert %s %s +append %s", escapeshellarg($img1_path), escapeshellarg($img2_path), escapeshellarg($imgCombined_path));
    exec($cmd, $outp, $retval);
    if ($retval != 0) {
        // Detect and handle command failure
        throw new Exception("Command \"{$cmd}\" returned {$retval}." . implode("\n", $outp));
    }
    $img = new EscposImage($imgCombined_path);
    // Setup the printer
    $connector = new FilePrintConnector("php://stdout");
    $profile = DefaultCapabilityProfile::getInstance();
    // Run the actual print
    $printer = new Printer($connector, $profile);
    try {
        $printer->setJustification(Printer::JUSTIFY_CENTER);
        $printer->graphics($img);
        $printer->cut();
    } finally {
        // Always close the connection
        $printer->close();
    }
} catch (Exception $e) {
    // Print out any errors: Eg. printer connection, image loading & external image manipulation.
    echo $e->getMessage() . "\n";
    echo $e->getTraceAsString();
} finally {
    unlink($imgCombined_path);
    unlink($tmpf_path);
Example #27
-1
 *
 * If this is correctly set up for your printer, then the driver will try its
 * best to map UTF-8 text into these code pages for you, allowing you to accept
 * arbitrary input from a database, without worrying about encoding it for the printer.
 */
require __DIR__ . '/../autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
use Mike42\Escpos\CapabilityProfiles\DefaultCapabilityProfile;
// Enter connector and capability profile (to match your printer)
$connector = new FilePrintConnector("php://stdout");
$profile = DefaultCapabilityProfile::getInstance();
$verbose = false;
// Skip tables which iconv wont convert to (ie, only print characters available with UTF-8 input)
/* Print a series of receipts containing i18n example strings - Code below shouldn't need changing */
$printer = new Mike42\Escpos\Printer($connector, $profile);
$codePages = $profile->getCodePages();
$first = true;
// Print larger table for first code-page.
foreach ($codePages as $table => $page) {
    /* Change printer code page */
    $printer->selectCharacterTable(255);
    $printer->selectCharacterTable($table);
    /* Select & print a label for it */
    $label = $page->getId();
    if (!$page->isEncodable()) {
        $label = " (not supported)";
    }
    $printer->setEmphasis(true);
    $printer->textRaw("Table {$table}: {$label}\n");
    $printer->setEmphasis(false);
Example #28
-4
<?php

require __DIR__ . '/../../autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
$a = "{A012323392982";
$b = "{B012323392982";
$c = "{C" . chr(01) . chr(23) . chr(23) . chr(39) . chr(29) . chr(82);
$connector = new FilePrintConnector("php://stdout");
$printer = new Printer($connector);
$printer->setJustification(Printer::JUSTIFY_CENTER);
$printer->setBarcodeHeight(48);
$printer->setBarcodeTextPosition(Printer::BARCODE_TEXT_BELOW);
foreach (array($a, $b, $c) as $item) {
    $printer->barcode($item, Printer::BARCODE_CODE128);
    $printer->feed(1);
}
$printer->cut();
$printer->close();