recreate project

This commit is contained in:
root
2026-02-10 22:11:06 -05:00
commit 663c0cdbda
10149 changed files with 1379710 additions and 0 deletions
+26
View File
@@ -0,0 +1,26 @@
Examples
--------
This folder contains a collectoion of feature examples.
Generally, demo.php is the fastest way to find out which features your
printer supports.
## Subfolders
- `interface/` - contains examples for output interfaces: eg, parallel, serial, USB, network, file-based.
- `specific/` - examples made in response to issues & questions. These cover specific languages, printers and interfaces, so hit narrower use cases.
## List of examples
Each example prints to standard output, so either edit the print connector, or redirect the output to your printer to see it in action. They are designed for developers: open them in a text editor before you run them!
- `bit-image.php` - Prints a images to the printer using the older "bit image" commands.
- `demo.php` - Demonstrates output using a large subset of availale features.
- `qr-code.php` - Prints QR codes, if your printer supports it.
- `character-encodings.php` - Shows available character encodings. Change from the DefaultCapabilityProfile to get more useful output for your specific printer.
- `graphics.php` - The same output as `bit-image.php`, printed with the newer graphics commands (not supported on many non-Epson printers)
- `receipt-with-logo.php` - A simple receipt containing a logo and basic formating.
- `character-encodings-with-images.php` - The same as `character-encodings.php`, but also prints each string using an `ImagePrintBuffer`, showing compatibility gaps.
- `print-from-html.php` - Runs `wkhtmltoimage` to convert HTML to an image, and then prints the image. (This is very slow)
- `character-tables.php` - Prints a compact character code table for each available character set. Used to debug incorrect output from `character-encodings.php`.
- `print-from-pdf.php` - Loads a PDF and prints each page in a few different ways (very slow as well)
- `rawbt-receipt` (.php & .html) - Demonstration of Back and Front for integration between the site and the Android application “RawBT - Printer Driver for Android”
+207
View File
@@ -0,0 +1,207 @@
<?php
require __DIR__ . '/../vendor/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);
$printer->text("Text position\n");
$printer->selectPrintMode();
$hri = array (
Printer::BARCODE_TEXT_NONE => "No text",
Printer::BARCODE_TEXT_ABOVE => "Above",
Printer::BARCODE_TEXT_BELOW => "Below",
Printer::BARCODE_TEXT_ABOVE | Printer::BARCODE_TEXT_BELOW => "Both"
);
foreach ($hri as $position => $caption) {
$printer->text($caption . "\n");
$printer->setBarcodeTextPosition($position);
$printer->barcode("012345678901", Printer::BARCODE_JAN13);
$printer->feed();
}
/* Barcode types */
$standards = array (
Printer::BARCODE_UPCA => array (
"title" => "UPC-A",
"caption" => "Fixed-length numeric product barcodes.",
"example" => array (
array (
"caption" => "12 char numeric including (wrong) check digit.",
"content" => "012345678901"
),
array (
"caption" => "Send 11 chars to add check digit automatically.",
"content" => "01234567890"
)
)
),
Printer::BARCODE_UPCE => array (
"title" => "UPC-E",
"caption" => "Fixed-length numeric compact product barcodes.",
"example" => array (
array (
"caption" => "6 char numeric - auto check digit & NSC",
"content" => "123456"
),
array (
"caption" => "7 char numeric - auto check digit",
"content" => "0123456"
),
array (
"caption" => "8 char numeric",
"content" => "01234567"
),
array (
"caption" => "11 char numeric - auto check digit",
"content" => "01234567890"
),
array (
"caption" => "12 char numeric including (wrong) check digit",
"content" => "012345678901"
)
)
),
Printer::BARCODE_JAN13 => array (
"title" => "JAN13/EAN13",
"caption" => "Fixed-length numeric barcodes.",
"example" => array (
array (
"caption" => "12 char numeric - auto check digit",
"content" => "012345678901"
),
array (
"caption" => "13 char numeric including (wrong) check digit",
"content" => "0123456789012"
)
)
),
Printer::BARCODE_JAN8 => array (
"title" => "JAN8/EAN8",
"caption" => "Fixed-length numeric barcodes.",
"example" => array (
array (
"caption" => "7 char numeric - auto check digit",
"content" => "0123456"
),
array (
"caption" => "8 char numeric including (wrong) check digit",
"content" => "01234567"
)
)
),
Printer::BARCODE_CODE39 => array (
"title" => "Code39",
"caption" => "Variable length alphanumeric w/ some special chars.",
"example" => array (
array (
"caption" => "Text, numbers, spaces",
"content" => "ABC 012"
),
array (
"caption" => "Special characters",
"content" => "$%+-./"
),
array (
"caption" => "Extra char (*) Used as start/stop",
"content" => "*TEXT*"
)
)
),
Printer::BARCODE_ITF => array (
"title" => "ITF",
"caption" => "Variable length numeric w/even number of digits,\nas they are encoded in pairs.",
"example" => array (
array (
"caption" => "Numeric- even number of digits",
"content" => "0123456789"
)
)
),
Printer::BARCODE_CODABAR => array (
"title" => "Codabar",
"caption" => "Varaible length numeric with some allowable\nextra characters. ABCD/abcd must be used as\nstart/stop characters (one at the start, one\nat the end) to distinguish between barcode\napplications.",
"example" => array (
array (
"caption" => "Numeric w/ A A start/stop. ",
"content" => "A012345A"
),
array (
"caption" => "Extra allowable characters",
"content" => "A012$+-./:A"
)
)
),
Printer::BARCODE_CODE93 => array (
"title" => "Code93",
"caption" => "Variable length- any ASCII is available",
"example" => array (
array (
"caption" => "Text",
"content" => "012abcd"
)
)
),
Printer::BARCODE_CODE128 => array (
"title" => "Code128",
"caption" => "Variable length- any ASCII is available",
"example" => array (
array (
"caption" => "Code set A uppercase & symbols",
"content" => "{A" . "012ABCD"
),
array (
"caption" => "Code set B general text",
"content" => "{B" . "012ABCDabcd"
),
array (
"caption" => "Code set C compact numbers\n Sending chr(21) chr(32) chr(43)",
"content" => "{C" . chr(21) . chr(32) . chr(43)
)
)
)
);
$printer->setBarcodeTextPosition(Printer::BARCODE_TEXT_BELOW);
foreach ($standards as $type => $standard) {
$printer->selectPrintMode(Printer::MODE_DOUBLE_HEIGHT | Printer::MODE_DOUBLE_WIDTH);
$printer->text($standard ["title"] . "\n");
$printer->selectPrintMode();
$printer->text($standard ["caption"] . "\n\n");
foreach ($standard ["example"] as $id => $barcode) {
$printer->setEmphasis(true);
$printer->text($barcode ["caption"] . "\n");
$printer->setEmphasis(false);
$printer->text("Content: " . $barcode ["content"] . "\n");
$printer->barcode($barcode ["content"], $type);
$printer->feed();
}
}
$printer->cut();
$printer->close();
+36
View File
@@ -0,0 +1,36 @@
<?php
/* Example print-outs using the older bit image print command */
require __DIR__ . '/../vendor/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();
@@ -0,0 +1,63 @@
<?php
/* Change to the correct path if you copy this example! */
require __DIR__ . '/../vendor/autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
use Mike42\Escpos\PrintBuffers\EscposPrintBuffer;
use Mike42\Escpos\PrintBuffers\ImagePrintBuffer;
use Mike42\Escpos\CapabilityProfile;
/**
* This example builds on character-encodings.php, also providing an image-based rendering.
* This is quite slow, since a) the buffers are changed dozens of
* times in the example, and b) It involves sending very wide images, which printers don't like!
*
* There are currently no test cases around the image printing, since it is an experimental feature.
*
* It does, however, illustrate the way that more encodings are available when image output is used.
*/
include(dirname(__FILE__) . '/resources/character-encoding-test-strings.inc');
try {
// Enter connector and capability profile
$connector = new FilePrintConnector("php://stdout");
$profile = CapabilityProfile::load('default');
$buffers = array(new EscposPrintBuffer(), new ImagePrintBuffer());
/* 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);
foreach ($buffers as $buffer) {
$printer -> setPrintBuffer($buffer);
$printer -> text($str);
}
$printer -> setPrintBuffer($buffers[0]);
}
$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);
$printer -> text($label . ":\n");
$printer -> setEmphasis(false);
foreach ($buffers as $buffer) {
$printer -> setPrintBuffer($buffer);
$printer -> text($str);
}
$printer -> setPrintBuffer($buffers[0]);
}
$printer -> cut();
/* Close printer */
$printer -> close();
} catch (Exception $e) {
echo "Couldn't print to this printer: " . $e -> getMessage() . "\n";
}
@@ -0,0 +1,60 @@
<?php
/* Change to the correct path if you copy this example! */
require __DIR__ . '/../vendor/autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
use Mike42\Escpos\CapabilityProfile;
/**
* This demonstrates available character encodings. Escpos-php accepts UTF-8,
* and converts this to lower-level data to the printer. This is a complex area, so be
* prepared to code a model-specific hack ('CapabilityProfile') for your printer.
*
* If you run into trouble, please file an issue on GitHub, including at a minimum:
* - A UTF-8 test string in the language you're working in, and
* - A test print or link to a technical document which lists the available
* 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 = CapabilityProfile::load("default");
/* 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);
$printer -> text($label . ":\n");
$printer -> setEmphasis(false);
$printer -> text($str);
}
$printer -> cut();
/* Close printer */
$printer -> close();
} catch (Exception $e) {
echo "Couldn't print to this printer: " . $e -> getMessage() . "\n";
}
+75
View File
@@ -0,0 +1,75 @@
<?php
/**
* This demo prints out supported code pages on your printer. This is intended
* for debugging character-encoding issues: If your printer does not work with
* a built-in capability profile, you need to check its documentation for
* supported code pages.
*
* These are then loaded into a capability profile, which maps code page
* numbers to iconv encoding names on your particular printer. This script
* will print all configured code pages, so that you can check that the chosen
* iconv encoding name matches the actual code page contents.
*
* 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__ . '/../vendor/autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
use Mike42\Escpos\CapabilityProfile;
// Enter connector and capability profile (to match your printer)
$connector = new FilePrintConnector("php://stdout");
$profile = CapabilityProfile::load("default");
$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);
if (!$page -> isEncodable() && !$verbose) {
continue; // Skip non-recognised
}
/* Print a table of available characters (first table is larger than subsequent ones */
if ($first) {
$first = false;
compactCharTable($printer, 1, true);
} else {
compactCharTable($printer);
}
}
$printer -> cut();
$printer -> close();
function compactCharTable($printer, $start = 4, $header = false)
{
/* Output a compact character table for the current encoding */
$chars = str_repeat(' ', 256);
for ($i = 0; $i < 255; $i++) {
$chars[$i] = ($i > 32 && $i != 127) ? chr($i) : ' ';
}
if ($header) {
$printer -> setEmphasis(true);
$printer -> textRaw(" 0123456789ABCDEF0123456789ABCDEF\n");
$printer -> setEmphasis(false);
}
for ($y = $start; $y < 8; $y++) {
$printer -> setEmphasis(true);
$printer -> textRaw(strtoupper(dechex($y * 2)) . " ");
$printer -> setEmphasis(false);
$printer -> textRaw(substr($chars, $y * 32, 32) . "\n");
}
}
+51
View File
@@ -0,0 +1,51 @@
<?php
/**
* This demo interacts with an Aures OCD-300 customer display,
* showing its support for ESC/POS text encodings.
*/
require __DIR__ . '/../vendor/autoload.php';
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
use Mike42\Escpos\CapabilityProfile;
use Mike42\Escpos\Printer;
use Mike42\Escpos\Devices\AuresCustomerDisplay;
/*
* Device appears as a serial port.
*
* stat /dev/ttyACM0
* sudo usermod -a -G dialout [username]
*/
$connector = new FilePrintConnector("/dev/ttyACM0");
// Profile and display
$profile = CapabilityProfile::load("OCD-300");
$display = new AuresCustomerDisplay($connector, $profile);
// Make a really long test string
include(__DIR__ . "/resources/character-encoding-test-strings.inc");
$input = "";
foreach ($inputsOk as $str) {
$input .= $str;
}
// Wrap at a fixed width (as ASCII...), and show the user
// what's about to be sent to the printer
$wrapped = wordwrap($input, 20);
echo($wrapped);
// Roll out each line with 0.5s delay
foreach (explode("\n", $wrapped) as $line) {
$display -> feed();
$display -> text($line);
usleep(500000);
}
// Finish by showing "Hello World"
$display -> clear();
$display -> text("Hello World\n");
// Dont forget to close the device
$display -> close();
+171
View File
@@ -0,0 +1,171 @@
<?php
/**
* 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 <michael.billington@gmail.com>
*/
require __DIR__ . '/../vendor/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);
for ($i = 0; $i < pow(2, count($modes)); $i++) {
$bits = str_pad(decbin($i), count($modes), "0", STR_PAD_LEFT);
$mode = 0;
for ($j = 0; $j < strlen($bits); $j++) {
if (substr($bits, $j, 1) == "1") {
$mode |= $modes[$j];
}
}
$printer -> selectPrintMode($mode);
$printer -> text("ABCDEFGHIJabcdefghijk\n");
}
$printer -> selectPrintMode(); // Reset
$printer -> cut();
/* Underline */
for ($i = 0; $i < 3; $i++) {
$printer -> setUnderline($i);
$printer -> text("The quick brown fox jumps over the lazy dog\n");
}
$printer -> setUnderline(0); // Reset
$printer -> cut();
/* Cuts */
$printer -> text("Partial cut\n(not available on all printers)\n");
$printer -> cut(Printer::CUT_PARTIAL);
$printer -> text("Full cut\n");
$printer -> cut(Printer::CUT_FULL);
/* Emphasis */
for ($i = 0; $i < 2; $i++) {
$printer -> setEmphasis($i == 1);
$printer -> text("The quick brown fox jumps over the lazy dog\n");
}
$printer -> setEmphasis(false); // Reset
$printer -> cut();
/* Double-strike (looks basically the same as emphasis) */
for ($i = 0; $i < 2; $i++) {
$printer -> setDoubleStrike($i == 1);
$printer -> text("The quick brown fox jumps over the lazy dog\n");
}
$printer -> setDoubleStrike(false);
$printer -> cut();
/* Fonts (many printers do not have a 'Font C') */
$fonts = array(
Printer::FONT_A,
Printer::FONT_B,
Printer::FONT_C);
for ($i = 0; $i < count($fonts); $i++) {
$printer -> setFont($fonts[$i]);
$printer -> text("The quick brown fox jumps over the lazy dog\n");
}
$printer -> setFont(); // Reset
$printer -> cut();
/* Justification */
$justification = array(
Printer::JUSTIFY_LEFT,
Printer::JUSTIFY_CENTER,
Printer::JUSTIFY_RIGHT);
for ($i = 0; $i < count($justification); $i++) {
$printer -> setJustification($justification[$i]);
$printer -> text("A man a plan a canal panama\n");
}
$printer -> setJustification(); // Reset
$printer -> cut();
/* Barcodes - see barcode.php for more detail */
$printer -> setBarcodeHeight(80);
$printer->setBarcodeTextPosition(Printer::BARCODE_TEXT_BELOW);
$printer -> barcode("9876");
$printer -> feed();
$printer -> cut();
/* Graphics - this demo will not work on some non-Epson printers */
try {
$logo = EscposImage::load("resources/escpos-php.png", false);
$imgModes = array(
Printer::IMG_DEFAULT,
Printer::IMG_DOUBLE_WIDTH,
Printer::IMG_DOUBLE_HEIGHT,
Printer::IMG_DOUBLE_WIDTH | Printer::IMG_DOUBLE_HEIGHT
);
foreach ($imgModes as $mode) {
$printer -> graphics($logo, $mode);
}
} catch (Exception $e) {
/* Images not supported on your PHP, or image file not found */
$printer -> text($e -> getMessage() . "\n");
}
$printer -> cut();
/* Bit image */
try {
$logo = EscposImage::load("resources/escpos-php.png", false);
$imgModes = array(
Printer::IMG_DEFAULT,
Printer::IMG_DOUBLE_WIDTH,
Printer::IMG_DOUBLE_HEIGHT,
Printer::IMG_DOUBLE_WIDTH | Printer::IMG_DOUBLE_HEIGHT
);
foreach ($imgModes as $mode) {
$printer -> bitImage($logo, $mode);
}
} catch (Exception $e) {
/* Images not supported on your PHP, or image file not found */
$printer -> text($e -> getMessage() . "\n");
}
$printer -> cut();
/* QR Code - see also the more in-depth demo at qr-code.php */
$testStr = "Testing 123";
$models = array(
Printer::QR_MODEL_1 => "QR Model 1",
Printer::QR_MODEL_2 => "QR Model 2 (default)",
Printer::QR_MICRO => "Micro QR code\n(not supported on all printers)");
foreach ($models as $model => $name) {
$printer -> qrCode($testStr, Printer::QR_ECLEVEL_L, 3, $model);
$printer -> text("$name\n");
$printer -> feed();
}
$printer -> cut();
/* Pulse */
$printer -> pulse();
/* Always close the printer! On some PrintConnectors, no actual
* data is sent until the printer is closed. */
$printer -> close();
+36
View File
@@ -0,0 +1,36 @@
<?php
/* Print-outs using the newer graphics print command */
require __DIR__ . '/../vendor/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();
+8
View File
@@ -0,0 +1,8 @@
Interfaces
----------
This directory contains boilerpalte code to show you how to open a print connector
to printers which are connected in different ways.
To get a list of supported interfaces and operating systems, see the main README.md file for the project.
If you have a printer interface with no example, and you want to help put one together, then please lodge a request on the bug tracker: https://github.com/mike42/escpos-php/issues
+19
View File
@@ -0,0 +1,19 @@
<?php
/* Change to the correct path if you copy this example! */
require __DIR__ . '/../../vendor/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";
}
+22
View File
@@ -0,0 +1,22 @@
<?php
/* Change to the correct path if you copy this example! */
require __DIR__ . '/../../vendor/autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\NetworkPrintConnector;
/* Most printers are open on port 9100, so you just need to know the IP
* address of your receipt printer, and then fsockopen() it on that port.
*/
try {
$connector = new NetworkPrintConnector("10.x.x.x", 9100);
/* 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";
}
@@ -0,0 +1,33 @@
<?php
/* Change to the correct path if you copy this example! */
require __DIR__ . '/../../vendor/autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
/**
* On Linux, use the usblp module to make your printer available as a device
* file. This is generally the default behaviour if you don't install any
* vendor drivers.
*
* Once this is done, use a FilePrintConnector to open the device.
*
* Troubleshooting: On Debian, you must be in the lp group to access this file.
* dmesg to see what happens when you plug in your printer to make sure no
* other drivers are unloading the module.
*/
try {
// Enter the device file for your USB printer here
$connector = new FilePrintConnector("/dev/usb/lp0");
//$connector = new FilePrintConnector("/dev/usb/lp1");
//$connector = new FilePrintConnector("/dev/usb/lp2");
/* 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";
}
+52
View File
@@ -0,0 +1,52 @@
<?php
/* Change to the correct path if you copy this example! */
require __DIR__ . '/../../vendor/autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\WindowsPrintConnector;
/**
* Install the printer using USB printing support, and the "Generic / Text Only" driver,
* then share it.
*
* Use a WindowsPrintConnector with the share name to print. This works on either
* Windows or Linux.
*
* Troubleshooting: Fire up a command prompt/terminal, and ensure that (if your printer is
* shared as "Receipt Printer"), the following commands work.
*
* Windows: (use an appropriate "net use" command if you need authentication)
* echo "Hello World" > testfile
* ## If you need authentication, use "net use" to hook up the printer:
* # net use "\\computername\Receipt Printer" /user:Guest
* # net use "\\computername\Receipt Printer" /user:Bob secret
* # net use "\\computername\Receipt Printer" /user:workgroup\Bob secret
* copy testfile "\\computername\Receipt Printer"
* del testfile
*
* GNU/Linux:
* # No authentication
* echo "Hello World" | smbclient "//computername/Receipt Printer" -c "print -" -N
* # Guest login
* echo "Hello World" | smbclient "//computername/Receipt Printer" -U Guest -c "print -" -N
* # Basic username/password
* echo "Hello World" | smbclient "//computername/Receipt Printer" secret -U "Bob" -c "print -"
* # Including domain name
* echo "Hello World" | smbclient "//computername/Receipt Printer" secret -U "workgroup\\Bob" -c "print -"
*/
try {
// Enter the share name for your printer here, as a smb:// url format
$connector = new WindowsPrintConnector("smb://computername/Receipt Printer");
//$connector = new WindowsPrintConnector("smb://Guest@computername/Receipt Printer");
//$connector = new WindowsPrintConnector("smb://FooUser:secret@computername/workgroup/Receipt Printer");
//$connector = new WindowsPrintConnector("smb://User:secret@computername/Receipt Printer");
/* 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";
}
@@ -0,0 +1,31 @@
<?php
/* Change to the correct path if you copy this example! */
require __DIR__ . '/../../vendor/autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\WindowsPrintConnector;
/**
* Assuming your printer is available at LPT1,
* simpy instantiate a WindowsPrintConnector to it.
*
* When troubleshooting, make sure you can send it
* data from the command-line first:
* echo "Hello World" > LPT1
*/
try {
$connector = new WindowsPrintConnector("LPT1");
// A FilePrintConnector will also work, but on non-Windows systems, writes
// to an actual file called 'LPT1' rather than giving a useful error.
// $connector = new FilePrintConnector("LPT1");
/* 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";
}
@@ -0,0 +1,34 @@
<?php
/* Change to the correct path if you copy this example! */
require __DIR__ . '/../../vendor/autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\WindowsPrintConnector;
/**
* Install the printer using USB printing support, and the "Generic / Text Only" driver,
* then share it (you can use a firewall so that it can only be seen locally).
*
* Use a WindowsPrintConnector with the share name to print.
*
* Troubleshooting: Fire up a command prompt, and ensure that (if your printer is shared as
* "Receipt Printer), the following commands work:
*
* echo "Hello World" > testfile
* copy testfile "\\%COMPUTERNAME%\Receipt Printer"
* del testfile
*/
try {
// Enter the share name for your USB printer here
$connector = null;
//$connector = new WindowsPrintConnector("Receipt Printer");
/* 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";
}
@@ -0,0 +1,48 @@
<?php
/* Left margin & page width demo. */
require __DIR__ . '/../vendor/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);
/* Stuff around with page width */
$printer -> setEmphasis(true);
$printer -> text("Page width\n");
$printer -> setEmphasis(false);
$printer -> setJustification(Printer::JUSTIFY_RIGHT);
$printer -> text("Default width\n");
foreach(array(512, 256, 128, 64) as $width) {
$printer -> setPrintWidth($width);
$printer -> text("page width $width\n");
}
/* Printer shutdown */
$printer -> cut();
$printer -> close();
+95
View File
@@ -0,0 +1,95 @@
<?php
/* Demonstration of available options on the pdf417Code() command */
require __DIR__ . '/../vendor/autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
$connector = new FilePrintConnector("php://stdout");
$printer = new Printer($connector);
// Most simple example
title($printer, "PDF417 code demo\n");
$testStr = "Testing 123";
$printer -> pdf417Code($testStr);
$printer -> text("Most simple example\n");
$printer -> feed();
// Demo that alignment is the same as text
$printer -> setJustification(Printer::JUSTIFY_CENTER);
$printer -> pdf417Code($testStr, 3, 3, 2);
$printer -> text("Same content, narrow and centred\n");
$printer -> setJustification();
$printer -> feed();
// Demo of error correction
title($printer, "Error correction\n");
$ec = array(0.1, 0.5, 1.0, 2.0, 4.0);
foreach ($ec as $level) {
$printer -> pdf417Code($testStr, 3, 3, 0, $level);
$printer -> text("Error correction ratio $level\n");
$printer -> feed();
}
// Change size
title($printer, "Pixel size\n");
$sizes = array(
2 => "(minimum)",
3 => "(default)",
4 => "",
8 => "(maximum)");
foreach ($sizes as $size => $label) {
$printer -> pdf417Code($testStr, $size);
$printer -> text("Module width $size dots $label\n");
$printer -> feed();
}
// Change height
title($printer, "Height multiplier\n");
$sizes = array(
2 => "(minimum)",
3 => "(default)",
4 => "",
8 => "(maximum)");
foreach ($sizes as $size => $label) {
$printer -> pdf417Code($testStr, 3, $size);
$printer -> text("Height multiplier $size $label\n");
$printer -> feed();
}
// Chage data column count
title($printer, "Data column count\n");
$columnCounts = array(
0 => "(auto, default)",
1 => "",
2 => "",
3 => "",
4 => "",
5 => "",
30 => "(maximum, doesnt fit!)");
foreach ($columnCounts as $columnCount => $label) {
$printer -> pdf417Code($testStr, 3, 3, $columnCount);
$printer -> text("Column count $columnCount $label\n");
$printer -> feed();
}
// Change options
title($printer, "Options\n");
$models = array(
Printer::PDF417_STANDARD => "Standard",
Printer::PDF417_TRUNCATED => "Truncated");
foreach ($models as $model => $name) {
$printer -> pdf417Code($testStr, 3, 3, 0, 0.10, $model);
$printer -> text("$name\n");
$printer -> feed();
}
// Cut & close
$printer -> cut();
$printer -> close();
function title(Printer $printer, $str)
{
$printer -> selectPrintMode(Printer::MODE_DOUBLE_HEIGHT | Printer::MODE_DOUBLE_WIDTH);
$printer -> text($str);
$printer -> selectPrintMode();
}
+86
View File
@@ -0,0 +1,86 @@
<?php
require __DIR__ . '/../vendor/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)
);
/* Test for dependencies */
foreach (array("xvfb-run", "wkhtmltoimage") as $cmd) {
$testCmd = sprintf("which %s", escapeshellarg($cmd));
exec($testCmd, $testOut, $testStatus);
if ($testStatus != 0) {
throw new Exception("You require $cmd but it could not be found");
}
}
/* Run wkhtmltoimage */
$descriptors = array(
1 => array("pipe", "w"),
2 => array("pipe", "w"),
);
$process = proc_open($command, $descriptors, $fd);
if (is_resource($process)) {
/* Read stdout */
$outputStr = stream_get_contents($fd[1]);
fclose($fd[1]);
/* Read stderr */
$errorStr = stream_get_contents($fd[2]);
fclose($fd[2]);
/* Finish up */
$retval = proc_close($process);
if ($retval != 0) {
throw new Exception("Command $cmd failed: $outputStr $errorStr");
}
} else {
throw new Exception("Command '$cmd' failed to start.");
}
/* Load up the image */
try {
$img = EscposImage::load($dest);
} catch (Exception $e) {
unlink($dest);
throw $e;
}
unlink($dest);
/* Print it */
$printer -> bitImage($img); // bitImage() seems to allow larger images than graphics() on the TM-T20. bitImageColumnFormat() is another option.
$printer -> cut();
} catch (Exception $e) {
echo $e -> getMessage();
} finally {
$printer -> close();
}
+78
View File
@@ -0,0 +1,78 @@
<?php
require __DIR__ . '/../vendor/autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\ImagickEscposImage;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
/*
* This is three examples in one:
* 1: Print an entire PDF, normal quality.
* 2: Print at a lower quality for speed increase (CPU & transfer)
* 3: Cache rendered documents for a speed increase (removes CPU image processing completely on subsequent prints)
*/
/* 1: Print an entire PDF, start-to-finish (shorter form of the example) */
$pdf = 'resources/document.pdf';
$connector = new FilePrintConnector("php://stdout");
$printer = new Printer($connector);
try {
$pages = ImagickEscposImage::loadPdf($pdf);
foreach ($pages as $page) {
$printer -> graphics($page);
}
$printer -> cut();
} catch (Exception $e) {
/*
* loadPdf() throws exceptions if files or not found, or you don't have the
* imagick extension to read PDF's
*/
echo $e -> getMessage() . "\n";
} finally {
$printer -> close();
}
/*
* 2: Speed up printing by roughly halving the resolution, and printing double-size.
* This gives a 75% speed increase at the expense of some quality.
*
* Reduce the page width further if necessary: if it extends past the printing area, your prints will be very slow.
*/
$connector = new FilePrintConnector("php://stdout");
$printer = new Printer($connector);
$pdf = 'resources/document.pdf';
$pages = ImagickEscposImage::loadPdf($pdf, 260);
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)));
}
+86
View File
@@ -0,0 +1,86 @@
<?php
/* Demonstration of available options on the qrCode() command */
require __DIR__ . '/../vendor/autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
$connector = new FilePrintConnector("php://stdout");
$printer = new Printer($connector);
// Most simple example
title($printer, "QR code demo\n");
$testStr = "Testing 123";
$printer -> qrCode($testStr);
$printer -> text("Most simple example\n");
$printer -> feed();
// Demo that alignment is the same as text
$printer -> setJustification(Printer::JUSTIFY_CENTER);
$printer -> qrCode($testStr);
$printer -> text("Same example, centred\n");
$printer -> setJustification();
$printer -> feed();
// Demo of numeric data being packed more densly
title($printer, "Data encoding\n");
$test = array(
"Numeric" => "0123456789012345678901234567890123456789",
"Alphanumeric" => "abcdefghijklmnopqrstuvwxyzabcdefghijklmn",
"Binary" => str_repeat("\0", 40));
foreach ($test as $type => $data) {
$printer -> qrCode($data);
$printer -> text("$type\n");
$printer -> feed();
}
// Demo of error correction
title($printer, "Error correction\n");
$ec = array(
Printer::QR_ECLEVEL_L => "L",
Printer::QR_ECLEVEL_M => "M",
Printer::QR_ECLEVEL_Q => "Q",
Printer::QR_ECLEVEL_H => "H");
foreach ($ec as $level => $name) {
$printer -> qrCode($testStr, $level);
$printer -> text("Error correction $name\n");
$printer -> feed();
}
// Change size
title($printer, "Pixel size\n");
$sizes = array(
1 => "(minimum)",
2 => "",
3 => "(default)",
4 => "",
5 => "",
10 => "",
16 => "(maximum)");
foreach ($sizes as $size => $label) {
$printer -> qrCode($testStr, Printer::QR_ECLEVEL_L, $size);
$printer -> text("Pixel size $size $label\n");
$printer -> feed();
}
// Change model
title($printer, "QR model\n");
$models = array(
Printer::QR_MODEL_1 => "QR Model 1",
Printer::QR_MODEL_2 => "QR Model 2 (default)",
Printer::QR_MICRO => "Micro QR code\n(not supported on all printers)");
foreach ($models as $model => $name) {
$printer -> qrCode($testStr, Printer::QR_ECLEVEL_L, 3, $model);
$printer -> text("$name\n");
$printer -> feed();
}
// Cut & close
$printer -> cut();
$printer -> close();
function title(Printer $printer, $str)
{
$printer -> selectPrintMode(Printer::MODE_DOUBLE_HEIGHT | Printer::MODE_DOUBLE_WIDTH);
$printer -> text($str);
$printer -> selectPrintMode();
}
+76
View File
@@ -0,0 +1,76 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>RawBT Integration Demo</title>
<meta content="width=device-width, initial-scale=1" name="viewport">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
html {
background-color: grey;
padding: 32px;
}
body {
max-width: 640px;
margin: 0 auto;
padding: 32px;
background-color: white;
}
button {
background-color: #6e89ff;
color: white;
padding: 16px;
border: none;
}
pre {
background-color: #f0f0f0;
border-left: #6e89ff solid 3px
}
p {
text-align: right;
}
a {
color: #6e89ff;
text-decoration: none;
}
a:before{
content: '\1F855';
margin-right:4px;
}
</style>
<script>
// for php demo call
function ajax_print(url, btn) {
b = $(btn);
b.attr('data-old', b.text());
b.text('wait');
$.get(url, function (data) {
window.location.href = data; // main action
}).fail(function () {
alert("ajax error");
}).always(function () {
b.text(b.attr('data-old'));
})
}
</script>
</head>
<body>
<img src="resources/rawbtlogo.png" alt="black & white picture">
<h1>RawBT Integration Demo</h1>
<pre>
window.location.href = ajax_backend_data;
</pre>
<br/>
<button onclick="ajax_print('rawbt-receipt.php',this)">RECEIPT</button>
<p><a href="https://rawbt.ru/">Visit RawBT site</a></p>
</body>
</html>
+145
View File
@@ -0,0 +1,145 @@
<?php
require __DIR__ . '/../autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\EscposImage;
use Mike42\Escpos\PrintConnectors\RawbtPrintConnector;
use Mike42\Escpos\CapabilityProfile;
try {
$profile = CapabilityProfile::load("POS-5890");
/* Fill in your own connector here */
$connector = new RawbtPrintConnector();
/* 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/rawbtlogo.png", false);
$printer = new Printer($connector, $profile);
/* Print top logo */
if ($profile->getSupportsGraphics()) {
$printer->graphics($logo);
}
if ($profile->getSupportsBitImageRaster() && !$profile->getSupportsGraphics()) {
$printer->bitImage($logo);
}
/* Name of shop */
$printer->setJustification(Printer::JUSTIFY_CENTER);
$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);
$printer->setEmphasis(true);
$printer->text(new item('', '$'));
$printer->setEmphasis(false);
foreach ($items as $item) {
$printer->text($item->getAsString(32)); // for 58mm Font A
}
$printer->setEmphasis(true);
$printer->text($subtotal->getAsString(32));
$printer->setEmphasis(false);
$printer->feed();
/* Tax and total */
$printer->text($tax->getAsString(32));
$printer->selectPrintMode(Printer::MODE_DOUBLE_WIDTH);
$printer->text($total->getAsString(32));
$printer->selectPrintMode();
/* Footer */
$printer->feed(2);
$printer->setJustification(Printer::JUSTIFY_CENTER);
$printer->text("Thank you for shopping\n");
$printer->text("at ExampleMart\n");
$printer->text("For trading hours,\n");
$printer->text("please visit example.com\n");
$printer->feed(2);
$printer->text($date . "\n");
/* Barcode Default look */
$printer->barcode("ABC", Printer::BARCODE_CODE39);
$printer->feed();
$printer->feed();
// Demo that alignment QRcode is the same as text
$printer2 = new Printer($connector); // dirty printer profile hack !!
$printer2->setJustification(Printer::JUSTIFY_CENTER);
$printer2->qrCode("https://rawbt.ru/mike42", Printer::QR_ECLEVEL_M, 8);
$printer2->text("rawbt.ru/mike42\n");
$printer2->setJustification();
$printer2->feed();
/* Cut the receipt and open the cash drawer */
$printer->cut();
$printer->pulse();
} catch (Exception $e) {
echo $e->getMessage();
} finally {
$printer->close();
}
/* A wrapper to do organise item names & prices into columns */
class item
{
private $name;
private $price;
private $dollarSign;
public function __construct($name = '', $price = '', $dollarSign = false)
{
$this->name = $name;
$this->price = $price;
$this->dollarSign = $dollarSign;
}
public function getAsString($width = 48)
{
$rightCols = 10;
$leftCols = $width - $rightCols;
if ($this->dollarSign) {
$leftCols = $leftCols / 2 - $rightCols / 2;
}
$left = str_pad($this->name, $leftCols);
$sign = ($this->dollarSign ? '$ ' : '');
$right = str_pad($sign . $this->price, $rightCols, ' ', STR_PAD_LEFT);
return "$left$right\n";
}
public function __toString()
{
return $this->getAsString();
}
}
+104
View File
@@ -0,0 +1,104 @@
<?php
require __DIR__ . '/../vendor/autoload.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");
/* 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);
$printer -> setEmphasis(true);
$printer -> text(new item('', '$'));
$printer -> setEmphasis(false);
foreach ($items as $item) {
$printer -> text($item);
}
$printer -> setEmphasis(true);
$printer -> text($subtotal);
$printer -> setEmphasis(false);
$printer -> feed();
/* Tax and total */
$printer -> text($tax);
$printer -> selectPrintMode(Printer::MODE_DOUBLE_WIDTH);
$printer -> text($total);
$printer -> selectPrintMode();
/* Footer */
$printer -> feed(2);
$printer -> setJustification(Printer::JUSTIFY_CENTER);
$printer -> text("Thank you for shopping at ExampleMart\n");
$printer -> text("For trading hours, please visit example.com\n");
$printer -> feed(2);
$printer -> text($date . "\n");
/* Cut the receipt and open the cash drawer */
$printer -> cut();
$printer -> pulse();
$printer -> close();
/* A wrapper to do organise item names & prices into columns */
class item
{
private $name;
private $price;
private $dollarSign;
public function __construct($name = '', $price = '', $dollarSign = false)
{
$this -> name = $name;
$this -> price = $price;
$this -> dollarSign = $dollarSign;
}
public function __toString()
{
$rightCols = 10;
$leftCols = 38;
if ($this -> dollarSign) {
$leftCols = $leftCols / 2 - $rightCols / 2;
}
$left = str_pad($this -> name, $leftCols) ;
$sign = ($this -> dollarSign ? '$ ' : '');
$right = str_pad($sign . $this -> price, $rightCols, ' ', STR_PAD_LEFT);
return "$left$right\n";
}
}
@@ -0,0 +1,35 @@
<?php
/* All strings from EscposPrintBufferTest are included below- These are fully supported
* on the default profile, so you can use them to test modified profiles (using the wrong
* profile for a printer produces mojibake) */
$inputsOk = array(
"Danish" => "Quizdeltagerne spiste jordbær med fløde, mens cirkusklovnen Wolther spillede på xylofon.\n",
"German" => "Falsches Üben von Xylophonmusik quält jeden größeren Zwerg.\n",
"Greek" => "Ξεσκεπάζω την ψυχοφθόρα βδελυγμία\n",
"English" => "The quick brown fox jumps over the lazy dog.\n",
"Spanish" => "El pingüino Wenceslao hizo kilómetros bajo exhaustiva lluvia y frío, añoraba a su querido cachorro.\n",
"French" => "Le cœur déçu mais l'âme plutôt naïve, Louÿs rêva de crapaüter en canoë au delà des îles, près du mälström où brûlent les novæ.\n",
"Irish Gaelic" => "D'fhuascail Íosa, Úrmhac na hÓighe Beannaithe, pór Éava agus Ádhaimh.\n",
"Hungarian" => "Árvíztűrő tükörfúrógép.\n",
"Icelandic" => "Kæmi ný öxi hér ykist þjófum nú bæði víl og ádrepa.\n",
"Latvian" => "Glāžšķūņa rūķīši dzērumā čiepj Baha koncertflīģeļu vākus.\n",
"Polish" => "Pchnąć w tę łódź jeża lub ośm skrzyń fig.\n",
"Russian" => "В чащах юга жил бы цитрус? Да, но фальшивый экземпляр!\n",
"Turkish" => "Pijamalı hasta, yağız şoföre çabucak güvendi.\n",
"Japanese (Katakana half-width)" => implode("\n", array("イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム", "ウイノオクヤマ ケフコエテ アサキユメミシ エヒモセスン")) . "\n",
"Vietnamese" => "Tiếng Việt, còn gọi tiếng Việt Nam hay Việt ngữ, là ngôn ngữ của người Việt (người Kinh) và là ngôn ngữ chính thức tại Việt Nam.\n"
);
/*
* These strings are not expected to print correctly, if at all, even on an Epson printer. This is due to a mix of
* escpos driver, printer, and PHP language support issues.
*
* They are included here as a collection of things not yet implemented.
*/
$inputsNotOk = array(
"Thai (No character encoder available)" => "นายสังฆภัณฑ์ เฮงพิทักษ์ฝั่ง ผู้เฒ่าซึ่งมีอาชีพเป็นฅนขายฃวด ถูกตำรวจปฏิบัติการจับฟ้องศาล ฐานลักนาฬิกาคุณหญิงฉัตรชฎา ฌานสมาธิ\n",
"Japanese (Hiragana)" => implode("\n", array("いろはにほへとちりぬるを", " わかよたれそつねならむ", "うゐのおくやまけふこえて", "あさきゆめみしゑひもせす")) . "\n",
"Japanese (Katakana full-width)" => implode("\n", array("イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム", "ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン")) . "\n",
"Arabic (RTL not supported, encoding issues)" => "صِف خَلقَ خَودِ كَمِثلِ الشَمسِ إِذ بَزَغَت — يَحظى الضَجيعُ بِها نَجلاءَ مِعطارِ" . "\n",
"Hebrew (RTL not supported, line break issues)" => "דג סקרן שט בים מאוכזב ולפתע מצא לו חברה איך הקליטה" . "\n"
);
File diff suppressed because one or more lines are too long
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 370 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

@@ -0,0 +1,21 @@
<?php
require __DIR__ . '/../../vendor/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();
@@ -0,0 +1,54 @@
<?php
require __DIR__ . '/../../vendor/autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
/**
* This example shows how to send a custom command to the printer
*
* "ESC ( B" is the barcode function for Epson LX300 series.
* This is not part of standard ESC/POS, but it's a good example
* of how to send some binary to the driver.
*/
/* Barcode type is used in this script */
const EAN13 = 0;
/* Barcode properties */
$type = EAN13;
$content = "0075678164125";
/*
* Make the command.
* This is documented on page A-14 of:
* https://files.support.epson.com/pdf/lx300p/lx300pu1.pdf
*/
$m = chr(EAN13);
$n = intLowHigh(strlen($content), 2);
$barcodeCommand = Printer::ESC . "G(" . $m . $n . $content;
/* Send it off as usual */
$connector = new FilePrintConnector("php://output");
$printer = new Printer($connector);
$printer->getPrintConnector()->write($barcodeCommand);
$printer->cut();
$printer->close();
/**
* Generate two characters for a number: In lower and higher parts, or more parts as needed.
*
* @param int $input
* Input number
* @param int $length
* The number of bytes to output (1 - 4).
*/
function intLowHigh($input, $length)
{
$outp = "";
for ($i = 0; $i < $length; $i ++) {
$outp .= chr($input % 256);
$input = (int) ($input / 256);
}
return $outp;
}
?>
@@ -0,0 +1,35 @@
<?php
/*
* Example of one way you could load a PNG data URI into an EscposImage object
* without using a file.
*/
require __DIR__ . '/../../vendor/autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
use Mike42\Escpos\ImagickEscposImage;
// Data URI for a PNG image (red dot from https://en.wikipedia.org/wiki/Data_URI_scheme )
$uri = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==";
// Convert data URI to binary data
$imageBlob = base64_decode(explode(",", $uri)[1]);
// Give Imagick a filename with the correct extension to stop it from attempting
// to identify the format itself (this avoids CVE-20163714)
$imagick = new Imagick();
$imagick -> setResourceLimit(6, 1); // Prevent libgomp1 segfaults, grumble grumble.
$imagick -> readImageBlob($imageBlob, "input.png");
// Load Imagick straight into an EscposImage object
$im = new ImagickEscposImage();
$im -> readImageFromImagick($imagick);
// Do a test print to make sure that this EscposImage object has the right data
// (should see a tiny bullet point)
$connector = new FilePrintConnector("php://output");
$printer = new Printer($connector);
$printer -> bitImage($im);
$printer -> cut();
$printer -> close();
@@ -0,0 +1,28 @@
<?php
/*
* Example showing how to return binary data back to the user.
*
* This is intended for the "Star TSP650IIcloudPRNT" printer.
*/
require __DIR__ . '/../../vendor/autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\DummyPrintConnector;
use Mike42\Escpos\CapabilityProfile;
// Make sure you load a Star print connector or you may get gibberish.
$connector = new DummyPrintConnector();
$profile = CapabilityProfile::load("TSP600");
$printer = new Printer($connector);
$printer -> text("Hello world!\n");
$printer -> cut();
// Get the data out as a string
$data = $connector -> getData();
// Return it, check the manual for specifics.
header('Content-type: application/octet-stream');
header('Content-Length: '.strlen($data));
echo $data;
// Close the printer when done.
$printer -> close();
@@ -0,0 +1,25 @@
<?php
require __DIR__ . '/../../vendor/autoload.php';
use Mike42\Escpos\CapabilityProfile;
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
use Mike42\Escpos\PrintBuffers\ImagePrintBuffer;
/* This example shows the printing of Latvian text on the Star TUP 592 printer */
$profile = CapabilityProfile::load("SP2000");
/* 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();
@@ -0,0 +1,39 @@
<?php
require __DIR__ . '/../../vendor/autoload.php';
use Mike42\Escpos\CapabilityProfile;
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
/*
* This example shows how tok send a custom command to the printer-
* 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 = CapabilityProfile::load("default"); // 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
*/
@@ -0,0 +1,19 @@
<?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__ . '/../../vendor/autoload.php';
use Mike42\Escpos\CapabilityProfile;
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
$connector = new FilePrintConnector("php://output");
$profile = CapabilityProfile::load("simple"); // Works for Epson printers
$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();
@@ -0,0 +1,24 @@
<?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__ . '/../../vendor/autoload.php';
use Mike42\Escpos\CapabilityProfile;
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
$connector = new FilePrintConnector("/dev/usb/lp1");
$profile = CapabilityProfile::load("default");
$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();
@@ -0,0 +1,77 @@
<?php
require __DIR__ . '/../../vendor/autoload.php';
use Mike42\Escpos\CapabilityProfile;
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
use Mike42\Escpos\PrintBuffers\ImagePrintBuffer;
$profile = CapabilityProfile::load("default");
// This is a quick demo of currency symbol issues in #39.
/* Option 1: Native ESC/POS characters, depends on printer and is buggy. */
$connector = new FilePrintConnector("php://stdout");
$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();
/* 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("€ 9,95\n");
$printer -> text("£ 9.95\n");
$printer -> text("$ 9.95\n");
$printer -> text("¥ 9.95\n");
$printer -> cut();
$printer -> close();
/*
Option 3: If the printer is configured to print in a specific code
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 CapabilityProfile
{
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();
@@ -0,0 +1,35 @@
<?php
/* Example of printing the GBP pound symbol on a STAR TSP650
*
* In this example, it's shown how to check that your PHP files are actually being
* saved in unicode. Sections B) and C) are identical in UTF-8, but different
* if you are saving to a retro format like Windows-1252.
*/
// Adjust these to your environment
require __DIR__ . '/../../vendor/autoload.php';
use Mike42\Escpos\CapabilityProfile;
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
$connector = new FilePrintConnector("php://stdout");
// Start printer
$profile = CapabilityProfile::load("simple");
$printer = new Printer($connector, $profile);
// A) Raw pound symbol
// This is the most likely thing to work, and bypasses all the fancy stuff.
$printer -> textRaw("\x9C"); // based on position in CP437
$printer -> text(" 1.95\n");
// B) Manually encoded UTF8 pound symbol. Tests that the driver correctly
// encodes this as CP437.
$printer -> text(base64_decode("wqM=") . " 2.95\n");
// C) Pasted in file. Tests that your files are being saved as UTF-8, which
// escpos-php is able to convert automatically to a mix of code pages.
$printer -> text("£ 3.95\n");
$printer -> cut();
$printer -> close();
@@ -0,0 +1,19 @@
<?php
/* Example of Greek text on the P-822D */
require __DIR__ . '/../../vendor/autoload.php';
use Mike42\Escpos\CapabilityProfile;
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
// Setup the printer
$connector = new FilePrintConnector("php://stdout");
$profile = CapabilityProfile::load("P822D");
$printer = new Printer($connector, $profile);
// Print a Greek pangram
$text = "Ξεσκεπάζω την ψυχοφθόρα βδελυγμία";
$printer -> text($text . "\n");
$printer -> cut();
// Close the connection
$printer -> close();
@@ -0,0 +1,64 @@
<?php
/*
* Example of calling ImageMagick 'convert' to manipulate an image prior to printing.
*
* Written as an example to remind you to do four things-
* - escape your command-line arguments with escapeshellarg
* - close the printer
* - delete any temp files
* - detect and handle external command failure
*
* Note that image operations are slow. You can and should serialise an EscposImage
* object into some sort of cache if you will re-use the output.
*/
require __DIR__ . '/../../vendor/autoload.php';
use Mike42\Escpos\CapabilityProfile;
use Mike42\Escpos\Printer;
use Mike42\Escpos\EscposImage;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
// Paths to images to combine
$img1_path = dirname(__FILE__) . "/../resources/tux.png";
$img2_path = dirname(__FILE__) . "/../resources/escpos-php.png";
// Set up temp file with .png extension
$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 = EscposImage::load($imgCombined_path);
// Setup the printer
$connector = new FilePrintConnector("php://stdout");
$profile = CapabilityProfile::load("default");
// 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);
}
@@ -0,0 +1,74 @@
<?php
/*
* This example shows Arabic image-based output on the EPOS TEP 220m.
*
* Because escpos-php is not yet able to render Arabic correctly
* on thermal line printers, small images are generated and sent
* instead. This is a bit slower, and only limited formatting
* is currently available in this mode.
*
* Requirements are:
* - imagick extension (For the ImagePrintBuffer, which does not
* support gd at the time of writing)
* - ArPHP 4.0 (release date: Jan 8, 2016), available from SourceForge, for
* handling the layout for this example.
*/
require __DIR__ . '/../../vendor/autoload.php';
use Mike42\Escpos\CapabilityProfile;
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
use Mike42\Escpos\PrintBuffers\ImagePrintBuffer;
/*
* Drop Ar-php into the folder listed below:
*/
require_once(dirname(__FILE__) . "/../../I18N/Arabic.php");
$fontPath = dirname(__FILE__) . "/../../I18N/Arabic/Examples/GD/ae_AlHor.ttf";
/*
* Inputs are some text, line wrapping options, and a font size.
*/
$textUtf8 = "صِف خَلقَ خَودِ كَمِثلِ الشَمسِ إِذ بَزَغَت — يَحظى الضَجيعُ بِها نَجلاءَ مِعطارِ";
$maxChars = 50;
$fontSize = 28;
/*
* First, convert the text into LTR byte order with line wrapping,
* Using the Ar-PHP library.
*
* 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 = CapabilityProfile::load("TEP-200M");
$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();
@@ -0,0 +1,15 @@
<?php
require __DIR__ . '/../../vendor/autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
use Mike42\Escpos\CapabilityProfile;
$connector = new FilePrintConnector("php://stdout");
$profile = CapabilityProfile::load("default");
$printer = new Printer($connector, $profile);
$printer -> text("Μιχάλης Νίκος\n");
$printer -> cut();
$printer -> close();
?>
@@ -0,0 +1,21 @@
<?php
/*
* Example of two-color printing, tested on an epson TM-U220 with two-color ribbon installed.
*/
require __DIR__ . '/../../vendor/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(Printer::COLOR_2);
$printer -> text("Red?!\n");
$printer -> setColor(Printer::COLOR_1);
$printer -> text("Default color again?!\n");
$printer -> cut();
} finally {
/* Always close the printer! */
$printer -> close();
}
@@ -0,0 +1,28 @@
<?php
/*
* Example of dithering used in EscposImage by default, if you have Imagick loaded.
*/
require __DIR__ . '/../../vendor/autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\EscposImage;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
$connector = new FilePrintConnector("/dev/usb/lp0");
$printer = new Printer($connector);
try {
/* Load with optimisations enabled. If you have Imagick, this will get you
a nicely dithered image, which prints very quickly
*/
$img1 = EscposImage::load(__DIR__ . '/../resources/tulips.png');
$printer -> bitImage($img1);
/* Load with optimisations disabled, forcing the use of PHP to convert the
pixels, which uses a threshold and is much slower.
*/
$img2 = EscposImage::load(__DIR__ . '/../resources/tulips.png', false);
$printer -> bitImage($img2);
$printer -> cut();
} finally {
/* Always close the printer! */
$printer -> close();
}
+7
View File
@@ -0,0 +1,7 @@
Specific examples
-----------------
These examples are designed for specific combinations of language,
printer and interface.
They are documented here because the general examples all set up the printer in a similar way.
+65
View File
@@ -0,0 +1,65 @@
<?php
/**
* This print-out shows how large the available font sizes are. It is included
* separately due to the amount of text it prints.
*
* @author Michael Billington <michael.billington@gmail.com>
*/
require __DIR__ . '/../vendor/autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
$connector = new FilePrintConnector("php://stdout");
$printer = new Printer($connector);
/* Initialize */
$printer -> initialize();
/* Text of various (in-proportion) sizes */
title($printer, "Change height & width\n");
for ($i = 1; $i <= 8; $i++) {
$printer -> setTextSize($i, $i);
$printer -> text($i);
}
$printer -> text("\n");
/* Width changing only */
title($printer, "Change width only (height=4):\n");
for ($i = 1; $i <= 8; $i++) {
$printer -> setTextSize($i, 4);
$printer -> text($i);
}
$printer -> text("\n");
/* Height changing only */
title($printer, "Change height only (width=4):\n");
for ($i = 1; $i <= 8; $i++) {
$printer -> setTextSize(4, $i);
$printer -> text($i);
}
$printer -> text("\n");
/* Very narrow text */
title($printer, "Very narrow text:\n");
$printer -> setTextSize(1, 8);
$printer -> text("The quick brown fox jumps over the lazy dog.\n");
/* Very flat text */
title($printer, "Very wide text:\n");
$printer -> setTextSize(4, 1);
$printer -> text("Hello world!\n");
/* Very large text */
title($printer, "Largest possible text:\n");
$printer -> setTextSize(8, 8);
$printer -> text("Hello\nworld!\n");
$printer -> cut();
$printer -> close();
function title(Printer $printer, $text)
{
$printer -> selectPrintMode(Printer::MODE_EMPHASIZED);
$printer -> text("\n" . $text);
$printer -> selectPrintMode(); // Reset
}
@@ -0,0 +1,22 @@
<?php
require __DIR__ . '/../vendor/autoload.php';
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
use Mike42\Escpos\Printer;
use Mike42\Escpos\Experimental\Unifont\UnifontPrintBuffer;
$connector = new FilePrintConnector("php://stdout");
$printer = new Printer($connector);
// Use Unifont to render text
$unifontBuffer = new UnifontPrintBuffer("/usr/share/unifont/unifont.hex");
$printer -> setPrintBuffer($unifontBuffer);
// Most simple example
$printer->text("Hello\n");
$printer->setUpsideDown(true);
$printer->text("World\n");
$printer->cut();
$printer->close();
+16
View File
@@ -0,0 +1,16 @@
<?php
/* Demonstration of upside-down printing */
require __DIR__ . '/../vendor/autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
$connector = new FilePrintConnector("php://stdout");
$printer = new Printer($connector);
// Most simple example
$printer -> text("Hello\n");
$printer -> setUpsideDown(true);
$printer -> text("World\n");
$printer -> cut();
$printer -> close();